springboot使用redis实现消息队列

一、概念

消息队列分为两种模式,一种是发布订阅模式,一种是生产者消费者模式。

生产者消费者模式:生产者生产消息放到队列里,多个消费者同时监听队列,谁先抢到消息谁就会从队列中取走消息;即对于每个消息只能被最多一个消费者拥有。

发布者订阅者模式:发布者生产消息放到队列里,多个监听队列的消费者都会收到同一份消息;即正常情况下每个消费者收到的消息应该都是一样的。


二、生产者消费者实现

1.springboot添加依赖:

 <!--添加redis缓存依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.4</version>
        </dependency>

2.配置redis属性:这里的host、密码需要修改为redis的ip以及密码

server:
  port: 15004
spring:
    redis:
        database: 0      # Redis数据库索引(默认为0)
        host: redis.ip # Redis服务器地址
        port: 6379       # Redis服务器连接端口
        password: password       # Redis服务器连接密码(默认为空)
        timeout: 60       # 连接超时时间(毫秒)
        pool:
          max-active: 8  # 连接池最大连接数(使用负值表示没有限制)
          max-idle: 8    # 连接池中的最大空闲连接
          max-wait: -1   # 连接池最大阻塞等待时间(使用负值表示没有限制)
          min-idle: 0    # 连接池中的最小空闲连接

3.消费者类:

/**
 * Author: hezishan
 * Date: 2018/5/15.
 * Description:
 **/
public class RedisRecieve {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisRecieve.class);

    private CountDownLatch latch;

    @Autowired
    public RedisRecieve(CountDownLatch latch) {
        this.latch = latch;
    }
    //接收方法
    public void receiveMessage(String message) {
        LOGGER.info("Received <" + message + ">");
        latch.countDown();
    }

}

4.配置类:注入spring容器中

/**
 * Author: hezishan
 * Date: 2018/5/15.
 * Description:
 **/
@Configuration
public class RedisConfiguration {

    @Bean
    RedisRecieve receiver(CountDownLatch latch) {
        return new RedisRecieve(latch);
    }

    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }
//添加主题为chat的监听
    @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(RedisRecieve receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
}

5.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class SharedemoApplicationTests {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    CountDownLatch latch;

    @Test
    public void contextLoads() {
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                    for(int i=0;i<5;i++){
                        stringRedisTemplate.convertAndSend("chat", i+"-Hello from Redis!");
                    }
            }
        }).start();

        try {
          latch.await();
        }catch (Exception e){

        }



    }

}

6.结果:

2018-05-15 14:31:29.349  INFO 12312 --- [           main] c.e.sharedemo.SharedemoApplicationTests  : Started SharedemoApplicationTests in 3.902 seconds (JVM running for 5.571)
2018-05-15 14:31:29.471  INFO 12312 --- [    container-2] c.e.sharedemo.redis.demo2.RedisRecieve   : Received <0-Hello from Redis!>
2018-05-15 14:31:29.473  INFO 12312 --- [    container-3] c.e.sharedemo.redis.demo2.RedisRecieve   : Received <1-Hello from Redis!>
2018-05-15 14:31:29.477  INFO 12312 --- [    container-4] c.e.sharedemo.redis.demo2.RedisRecieve   : Received <2-Hello from Redis!>
2018-05-15 14:31:29.479  INFO 12312 --- [    container-5] c.e.sharedemo.redis.demo2.RedisRecieve   : Received <3-Hello from Redis!>
2018-05-15 14:31:29.485  INFO 12312 --- [    container-6] c.e.sharedemo.redis.demo2.RedisRecieve   : Received <4-Hello from Redis!>
2018-05-15 14:31:29.487  INFO 12312 --- [       Thread-3] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@5167268: startup date [Tue May 15 14:31:25 CST 2018]; root of context hierarchy
2018-05-15 14:31:29.490  INFO 12312 --- [       Thread-3] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 2147483647


阅读更多
个人分类: spring boot
上一篇http请求
下一篇使用jdbc连接数据库
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭