用户工具

站点工具


spring:redis

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

spring:redis [2018/08/09 22:42] (当前版本)
guest 创建
行 1: 行 1:
 +        <​dependency>​
 +            <​groupId>​org.springframework.boot</​groupId>​
 +            <​artifactId>​spring-boot-starter</​artifactId>​
 +        </​dependency>​
 +        <​dependency>​
 +            <​groupId>​org.springframework.boot</​groupId>​
 +            <​artifactId>​spring-boot-starter-data-redis</​artifactId>​
 +        </​dependency>​
 +
 +<​code>​
 +@SpringBootApplication
 +public class Application {
 +
 +        private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);​
 +
 +        @Bean
 +        RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,​
 +                        MessageListenerAdapter listenerAdapter) {
 +                RedisMessageListenerContainer container = new RedisMessageListenerContainer();​
 +                container.setConnectionFactory(connectionFactory);​
 +                container.addMessageListener(listenerAdapter,​ new PatternTopic("​chat"​));​
 +
 +                return container;
 +        }
 +        //​消息接收者适配器
 +        @Bean
 +        MessageListenerAdapter listenerAdapter(Receiver receiver) {
 +                return new MessageListenerAdapter(receiver,​ "​receiveMessage"​);​
 +        }
 +
 +        @Bean
 +        Receiver receiver(CountDownLatch latch) {
 +                return new Receiver(latch);​
 +        }
 +
 +        @Bean
 +        CountDownLatch latch() {
 +                return new CountDownLatch(1);​
 +        }
 +        //​消息发送工具类
 +        @Bean
 +        StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
 +                return new StringRedisTemplate(connectionFactory);​
 +        }
 +
 +        public static void main(String[] args) throws InterruptedException {
 +                ApplicationContext ctx = SpringApplication.run(Application.class,​ args);
 +
 +                StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);​
 +                CountDownLatch latch = ctx.getBean(CountDownLatch.class);​
 +
 +                LOGGER.info("​Sending message..."​);​
 +                template.convertAndSend("​chat",​ "Hello from Redis!"​);​
 +
 +                latch.await();​
 +                System.exit(0);​
 +        }
 +}
 +</​code>​
 +
 +消息接收者可以是普通对象
 +
 +<​code>​
 +public class Receiver {
 +    private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);​
 +
 +    private CountDownLatch latch;
 +
 +    @Autowired
 +    public Receiver(CountDownLatch latch) {
 +        this.latch = latch;
 +    }
 +
 +    public void receiveMessage(String message) {
 +        LOGGER.info("​Received <" + message + ">"​);​
 +        latch.countDown();​
 +    }
 +}
 +</​code>​
 +
 +
 +
  
spring/redis.txt · 最后更改: 2018/08/09 22:42 由 guest