package com.qmtt.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration public class RedisConfig { @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); setSerializer(template);// 设置序列化工具 template.afterPropertiesSet(); return template; } private void setSerializer(StringRedisTemplate template) { @SuppressWarnings({ "rawtypes", "unchecked" }) Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); } // 订阅pubsub:queue @Bean RedisMessageListenerContainer redisContainer(RedisConnectionFactory factory) { final RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(factory); MessageListenerAdapter listener = new MessageListenerAdapter(new RedisMessageListener()); container.addMessageListener(listener, new ChannelTopic("pubsub:queue")); return container; } public class RedisMessageListener implements MessageListener { @Override public void onMessage(final Message message, final byte[] pattern) { System.out.println("Message received: " + message.toString()); } } }
#redis相关配置 # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=127.0.0.1 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password=111 # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=100 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=20 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=10 # 连接超时时间(毫秒) spring.redis.timeout=0
原文地址:https://www.cnblogs.com/wujf/p/8473892.html
时间: 2024-11-04 11:29:46