pom:java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
代碼:redis
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.MessageListener; 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 public class RedisSubListenerConfig { @Bean MessageListenerAdapter messageListener() { //abstract methods overwrite return new MessageListenerAdapter((MessageListener) (message, pattern) -> { System.out.println("Message received: " + message.toString()); }); } @Bean RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(messageListener(), topic()); return container; } @Bean ChannelTopic topic() { return new ChannelTopic("messageQueue"); } }
測試類:spring
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; /** * @date 2019-05-25 10:59 */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class RedisTest { @Resource private StringRedisTemplate stringRedisTemplate; @Test public void test(){ stringRedisTemplate.convertAndSend("messageQueue","hello world"); } }