项目如何搭建略过,可以使用 Spring Initializr 或者其他 IDEA 创建一个新的 Spring Boot 项目,并添加相关依赖即可
创建 Redis 消息发布者
创建一个服务类用于发布消息:
@Service
public class RedisPublisherService {
@Autowired
private RedisTemplate redisTemplate;
public void publishMessage(String channel, String message) {
redisTemplate.convertAndSend(channel, message);
}
}
创建 Redis 消息订阅者
创建一个服务类用于监听消息:
@Service
public class RedisSubscriberService implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
String channel = message.getChannel().toString();
String data = new String(message.getBody());
System.out.println("Received message from channel " + channel + ": " + data);
}
}
消息监听器绑定监听指定通道
@Configuration
public class RedisConfig {
// 自定义的消息订阅监听器
@Resource
private RedisSubscriberService redisSubscriberService;
@Bean
public RedisTemplate
测试发布与订阅
创建一个测试类来测试发布和订阅功能:
@Component
public class RedisTestRunner implements CommandLineRunner {
@Autowired
private RedisPublisherService publisherService;
@Autowired
private RedisSubscriberService subscriberService;
@Override
public void run(String... args) throws Exception {
// 发布消息
publisherService.publishMessage("test-channel", "Hello, yian!");
publisherService.publishMessage("user-channel", "Hello, weilai!");
}
}