Spring with Redis 消息订阅和推送
1、pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、redis配置
# redis spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=xxxxx
3、推送
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; @Component public class RedisPublisher { private final StringRedisTemplate redisTemplate; public RedisPublisher(StringRedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public void publish(String channel, String message) { redisTemplate.convertAndSend(channel, message); } }
4、订阅
import xxx.RedisSubscriber; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; @Configuration @Slf4j public class RedisConfig { @Value("${redis.topic}") private String topic; @Bean public MessageListenerAdapter messageListenerAdapter(RedisSubscriber redisSubscriber) { return new MessageListenerAdapter(redisSubscriber); } @Bean public RedisMessageListenerContainer redisMessageListenerContainer( RedisConnectionFactory connectionFactory, MessageListenerAdapter messageListenerAdapter) { log.info("+++ subscriber => {}", this.topic); RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(messageListenerAdapter, new ChannelTopic(this.topic)); return container; } }
5、订阅后的解析
import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; import org.springframework.stereotype.Component; @Component @Slf4j public class RedisSubscriber implements MessageListener { @Override public void onMessage(Message message, byte[] pattern) { String channel = new String(message.getChannel()); String messageBody = new String(message.getBody()); log.info("{} => {} ", channel, messageBody); // 处理接收到的消息 } }
有些事情,没经历过不知道原理,没失败过不明白奥妙,没痛苦过不了解真谛。临渊羡鱼,不如退而结网!

浙公网安备 33010602011771号