Redis使用
# Redis使用
# 1.SpringBoot整合Redis
导入maven坐标依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
1
2
3
4
2
3
4
spring配置文件中导入redis相关参数
spring:
application:
name: springdataredis_demo
#Redis相关配置
redis:
host: localhost
port: 6379
#password: 123456
database: 0 #操作的是0号数据库
jedis:
#Redis连接池配置
pool:
max-active: 8 #最大连接数
max-wait: 1ms #连接池最大阻塞等待时间
max-idle: 4 #连接池中的最大空闲连接
min-idle: 0 #连接池中的最小空闲连接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 2.redis消息订阅发布
# redis事件发布端
redistemplate:通过配置方式注入Bean,设置默认序列化器fastjsonredisserializer,入参自动注入RedisConnectionFactory根据yml配置的redis端口建立链接。
RedisTemplate#convertAndSend:发布消息,指明接收方Topic通信信道,和消息内容。
# redis监听器
RedisConnectionFactory:负责设置连接参数,redis服务地址。
注入连接工厂Bean并修改配置,从注册中心拉取redis的端口IP信息(properties),创建Jedis客户端连接(不需要在assist重新配置redis服务地址)。
RedisMessageListenerContainer:注入消息监听器容器,需要设置连接工厂和监听器适配器。并将消息通信Topic与监听器适配器绑定。
MessageListenerAdapter:指明消息处理委托对象,以及消息处理方法(最终发布方的消息会被该方法接收)。
# 3.Redis序列化器
- JdkSerializationRedisSerializer
RedisTemplate默认序列化方式,前提是被序列化对象必须实现Serializable接口,序列化后保存的是字节序列。(序列化后结果庞大,占据redis内存)
- StringRedisSerializer
是StringRedisTemplate默认的序列化方式,只能对字符串进行序列化,无法对普通对象进行序列化,因此需要JSON.toJSONString进行转化。
- Jackson2JsonRedisSerializer
速度快不需要实现serializable接口,将对象序列化成json串进行存储。在序列化时需要提供序列化对象的.class类型信息。
注意:使用jackson或者genericJackson存在的坑
redisTemplate.opsForValue().set(key, 1L);
Long value = redisTemplate.opsForValue().get(key);
// 此时获得的值的类型为Integer类型, 直接进行强转会进行报错
// 其实这也不能说是序列化存在的问题,而是json的数字类型与java的数据类型不能兼容
1
2
3
4
2
3
4
这里给出一种序列化器配置:
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
/** 设置redis键和值的序列化器*/
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
/** 设置hash的序列化器*/
template.setHashKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57