基本信息
文件名称:SpringBoot整合Redis实现热点数据缓存的示例代码.docx
文件大小:17.73 KB
总页数:7 页
更新时间:2025-05-21
总字数:约5.63千字
文档摘要

SpringBoot整合Redis实现热点数据缓存的示例代码

我们以IDEA+SpringBoot作为Java中整合Redis的使用的测试环境

首先,我们需要导入Redis的maven依赖

!--Redis的maven依赖包--

dependency

groupIdorg.springframework.boot/groupId

artifactIdspring-boot-starter-data-redis/artifactId

/dependency

其次,我们需要在配置文件中配置你的Redis配置信息,我使用的是.yml文件格式

#redis配置

spring:

redis:

#r服务器地址

host:

#服务器端口

port:6379

#数据库索引(默认0)

database:0

#连接超时时间(毫秒)

timeout:10s

jedis:

pool:

#连接池中的最大空闲连接数

max-idle:8

#连接池中的最小空闲连接数

min-idle:0

#连接池最大连接数(使用负值表示没有限制)

max-active:8

#连接池最大阻塞等待时间(使用负值表示没有限制)

max-wait:-1

对redis做自定义配置

importcom.fasterxml.jackson.annotation.JsonAutoDetect;

importcom.fasterxml.jackson.annotation.JsonTypeInfo;

importcom.fasterxml.jackson.annotation.PropertyAccessor;

importcom.fasterxml.jackson.databind.ObjectMapper;

importcom.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;

importorg.springframework.cache.annotation.CachingConfigurerSupport;

importorg.springframework.context.annotation.Bean;

importorg.springframework.context.annotation.Configuration;

importorg.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

importorg.springframework.data.redis.core.RedisTemplate;

importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

importorg.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration

publicclassRedisConfigurerextendsCachingConfigurerSupport{

*redisTemplate序列化使用的jdkSerializeable,存储二进制字节码,所以自定义序列化类

@Bean

publicRedisTemplateString,ObjectredisTemplate(LettuceConnectionFactorylettuceConnectionFactory){

//配置redisTemplate

RedisTemplateString,ObjectredisTemplate=newRedisTemplate();

redisTemplate.setConnectionFactory(lettuceConnectionFactory);

//设置序列化

Jackson2JsonRedisSerializerObjectredisSerializer=getRedisSerializer();

//key序列化

redisTemplate.setKeySerializer(newStringRedisSerializer()