使用 Redis 作为消息队列
Redis 还可以用作消息队列,特别是通过其发布/订阅(Pub/Sub)机制。你可以使用 RedisTemplate
的 convertAndSend
方法发送消息,并使用 @RedisListener
注解监听消息。
发送消息
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class MessagePublisher {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void publishMessage(String channel, String message) {
redisTemplate.convertAndSend(channel, message);
}
}
监听消息
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.stereotype.Service;
@Service
public class MessageSubscriber {
@Autowired
private RedisMessageListenerContainer redisContainer;
public void subscribeToChannel(String channel) {
ChannelTopic topic = new ChannelTopic(channel);
redisContainer.addMessageListener((message, pattern) -> {
System.out.println("Received message: " + message.toString());
}, topic);
}
}