<!-- SpringBoot整合Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
# 配置redis spring.redis.host=localhost spring.redis.port=6379
/* * 自定义RedisTamplate * */ @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { // 将template 泛型设置为 <String, Object> RedisTemplate<String, Object> template = new RedisTemplate(); // 连接工厂,不必修改 template.setConnectionFactory(redisConnectionFactory); /* * 序列化设置 */ // key、hash的key 采用 String序列化方式 template.setKeySerializer(RedisSerializer.string()); template.setHashKeySerializer(RedisSerializer.string()); // value、hash的value 采用 Jackson 序列化方式 template.setValueSerializer(RedisSerializer.json()); template.setHashValueSerializer(RedisSerializer.json()); template.afterPropertiesSet(); return template; } }
/* * 发布者 * */ public interface Publisher { void sendMsg(String topic, String msg); }
@Service public class MyPublisher implements Publisher { @Autowired public RedisTemplate<String, Object> redisTemplate; @Override public void sendMsg(String topic, String msg) { redisTemplate.convertAndSend(topic, msg); } }
/* * 配置RedisMessageListenerContainer容器 * */ @Bean RedisMessageListenerContainer redisContainer(RedisConnectionFactory factory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(factory); return container; }
@Component public class MsgListener implements MessageListener { @Override public void onMessage(Message message, byte[] pattern) { System.out.println("Message received: " + message.toString()); } }
@Service public class SubScriber { @Autowired private RedisMessageListenerContainer container; public void subScribe(String topic){ //订阅频道 container.addMessageListener(new MsgListener(), new ChannelTopic(topic)); } }
@RestController public class MsgController { @Autowired private MyPublisher publisher; @Autowired private SubScriber subScriber; @RequestMapping("/sendMsg/{msg}") public String sendMsg(@PathVariable("msg") String msg){ publisher.sendMsg("mjj", msg); return "发布成功!"; } @RequestMapping("/subChannel/{topic}") public String subChannel(@PathVariable("topic") String topic){ subScriber.subScribe(topic); return "订阅成功!"; } }
localhost:8080/subChannel/mjj http://localhost:8080/sendMsg/123456
控制台输出: