- RedisConfig核心类,实现了Redis连接,订阅以及发布配置
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory);
@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);
template.afterPropertiesSet();
return template;
}
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("test"));
return container;
}
@Bean
public MessageListenerAdapter listenerAdapter(RedisReceiver redisReceiver) {
MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(redisReceiver, "receiveMessage");
Jackson2JsonRedisSerializer<TaskSynData> serializer = new Jackson2JsonRedisSerializer<>(TaskSynData.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(objectMapper);
messageListenerAdapter.setSerializer(serializer);
return messageListenerAdapter;
}
}
@Data
public class TaskSynData implements Serializable {
private static final long serialVersionUID = -1681130765215741845L;
private String name;
private String type;
}
@Resource
private RedisTemplate redisTemplate;
@RequestMapping(value = "/redis/send", method = RequestMethod.GET)
public String redisSend() {
TaskSynData taskSynData = new TaskSynData();
taskSynData.setType("type");
taskSynData.setName("测试");
redisTemplate.convertAndSend("test", taskSynData);
return "发送成功";
}
@Component
public class RedisReceiver {
public void receiveMessage(TaskSynData taskSynData ) {
System.out.println("收到消息为:" + taskSynData);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8a7d9e93b4c59c02e15ec77318c7e766.png)