SpringBoot基于Redis的发布订阅
1.导入Redis依赖
<!-- SpringBoot整合Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.修改Redis配置
# 配置redis
spring.redis.host=localhost
spring.redis.port=6379
3.自定义RedisTamplate
/*
* 自定义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;
}
}
4.发布者
Publisher接口
/*
* 发布者
* */
public interface Publisher {
void sendMsg(String topic, String msg);
}
Mypublisher类
@Service
public class MyPublisher implements Publisher {
@Autowired
public RedisTemplate<String, Object> redisTemplate;
@Override
public void sendMsg(String topic, String msg) {
redisTemplate.convertAndSend(topic, msg);
}
}
5.订阅者
1)配置RedisMessageListenerContainer容器
/*
* 配置RedisMessageListenerContainer容器
* */
@Bean
RedisMessageListenerContainer redisContainer(RedisConnectionFactory factory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(factory);
return container;
}
2)定义消息监听器,需要实现MessageListener接口
@Component
public class MsgListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
System.out.println("Message received: " + message.toString());
}
}
3)SubScriber订阅者类
@Service
public class SubScriber {
@Autowired
private RedisMessageListenerContainer container;
public void subScribe(String topic){
//订阅频道
container.addMessageListener(new MsgListener(), new ChannelTopic(topic));
}
}
6.测试Controller
@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
控制台输出: