1. 程式人生 > >SpringBoot2.X 整合RedisTemplate 簡單實現訊息佇列

SpringBoot2.X 整合RedisTemplate 簡單實現訊息佇列

首先:SpringBoot2 以上 整合redis與 Springboot1 有所區別,不用配置redis

在啟動的時候,容器中會根據application中redis的配置自動配置,可在專案裡直接引用RedisTemplate

下面是SpringBoot引用Redis的pom檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!--整合redis-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

下面實現訊息佇列:

準備兩個SpringBoot專案

①釋出訊息application:

server:
  port: 8010
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6378
    timeout: 20000

②只是一個demo 沒有service解耦,下面是controller

package com.example.demo.redis.controller;

import com.example.demo.entity.User;
import com.example.demo.redis.service.PubRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("/redis")
@Controller
public class RedisController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PubRedisService pubRedisService;
    @RequestMapping("/index")
    public User redisIndex() {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set("user", "user2");
        String str = ops.get("a");
        System.out.println("redis server str:" + str);
        return null;
    }

    /**
     * 釋出訊息
     * @param id
     * @return
     */
    @RequestMapping("/sendMessage/{id}")
    public String sendMessage(@PathVariable String id) {
        redisTemplate.convertAndSend("msg","哈哈哈,redis 訂閱資訊");
        return "";
    }
}

訊息釋出就完事了

接下來是接收訊息

server:
  port: 8010
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6378
    timeout: 20000

然後是接收訊息的配置

新建一個接收訊息的實體類

package com.example.demo.redis.entity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

/**
 * 接收訊息的實體類
 */
@Component
public class RedisMessage implements MessageListener {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
        String msg = serializer.deserialize(message.getBody());
        System.out.println("接收到的訊息是:" + msg);
    }
}

配置訊息adapter

package com.example.demo.redis.config;


import com.example.demo.redis.entity.RedisMessage;
import com.sun.istack.internal.tools.DefaultAuthenticator;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
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.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.concurrent.CountDownLatch;

/**
 * 訊息佇列  訂閱者  redis配置
 */
@Configuration
//@AutoConfigureAfter({RedisMessage.class})
public class RedisSubConfig {

    /**
     * 建立連線工廠
     *
     * @param connectionFactory
     * @param adapter
     * @return
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter adapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(adapter, new PatternTopic("msg"));
        return container;
    }

    /**
     * @param message
     * @return
     */
    @Bean
    public MessageListenerAdapter adapter(RedisMessage message){
        // onMessage 如果RedisMessage 中 沒有實現介面,這個引數必須跟RedisMessage中的讀取資訊的方法名稱一樣
        return new MessageListenerAdapter(message, "onMessage");
    }
}

訊息接收者已經定義好了

啟動redis server 和兩個SpringBoot專案  訪問釋出者的介面釋出訊息,訊息接收者就會自動接收發布者釋出的訊息,這個訊息佇列實時性很高