SpringCloud distributed micro-services b2b2c e-commerce - redis implement the message with the team in springboot

Preparation phase
installation redis, refer to my other article
the Java 1.8
Maven 3.0
IDEA
environment rely
create a new springboot engineering, architecture can understand springcloud add beg: 3536247259. Pom in its file, added spring-boot-starter-data- redis -dependent:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

Create a message recipient
REcevier class, which is a normal class, the need to inject into springboot.

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();
    }
}

Inject message recipient

@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);
    }

Injection message listener container
in spring data redis utilizing redis sends a message and receive one message requires three things:

A connection facility
a message listener container
Redis template
above step 3 has been completed, so that the container can only monitor message injection:

@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");
    }

Test
main method in springboot inlet:

public static void main(String[] args) throws Exception{
        ApplicationContext ctx =  SpringApplication.run(SpringbootRedisApplication.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);
    }

Guess you like

Origin blog.51cto.com/14622290/2464117