1. 程式人生 > >springboot使用redis實現訊息佇列

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.s[email protected]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