Springboot21 整合redis、利用redis實現消息隊列


 

1 前提准備

  1.1 創建一個springboot項目

    技巧01:本博文基於springboot2.0創建

  1.2 安裝redis

    1.2.1 linux版本

      參考博文

    1.2.2 windows版本

      到redis官網下載windows版本的壓縮包后,解壓即可

  1.3 redis使用

    本博文以window版本為例子,linux版本請參見

    1.3.1 開啟服務端

      》進入到解壓后的redis根目錄

        》執行 redis-server.exe

    1.3.2 開啟客戶端

      進入到redis解壓目錄 -> 執行 redis-cli.exe

    1.3.3 測試redis服務端和客戶端的通信

       在redis客戶端執行 ping,如果返回了 PONG 就表明redis前后端通信正常

    1.3.4 關閉

      客戶端和服務端都用 Ctrl + C 就可以關閉了

 

2 SpringBoot 集成 Redis

  2.1 創建一個SpringBoot項目

    技巧01:創建時引入 spring-boot-starter-web 和 spring-boot-starter-data-redis

<?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>cn.xiangxu</groupId>
    <artifactId>redis_pub_sub</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.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-data-redis</artifactId>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-data-redis-reactive</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.0</version>
        </dependency>


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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>
pom.xml

  2.2 配置redis服務器

    技巧01:springboot的啟動包已經給我們配置好了redis相關的配置類,所以我們只需要在配置文件中對redis服務器進行相關的配置即可

  2.3 使用redis服務器

    坑01:外部的redis客戶端在連接redis服務器時需要關閉redis服務器的守護進程,否則會出現連接失敗;修改redis.conf配置文件即可,windows版本的redis配置文件在根目錄下的 redis.windows.conf 中;將配置文件中protected-mode 配置值從 yes 改為 no 即可。

    技巧01:因為springboot已經為我們配置好了一切,所以我們直接調用  RedisTemplate 或者 StringRedisTemplate 的相關API就可以對redis服務器進行相關的操作了

    》依賴注入 RedisTemplate 或者 StringRedisTemplate 

    》利用依賴注入的  RedisTemplate 或者 StringRedisTemplate  對象進行操作即可

package cn.xiangxu.redis_pub_sub.web;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class TestControllerTest {

    /**
     * 依賴注入RedisTemplate,直接利用RedisTemplate操作redis即可
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void test01(){
        log.info("Hello Boy");

        // 設置數據
        redisTemplate.opsForValue().set("age", "33");

        // 獲取數據
        String result = redisTemplate.opsForValue().get("name");
        System.out.println(result.toString());
//        System.out.println(redisTemplate.getClientList());;
    }

}
View Code

 

3 SpringBoot 利用 Redis 實現隊列的效果

  3.1 流程介紹

    參考博文

  3.2 源代碼

package cn.xiangxu.redis_pub_sub.domain;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.CountDownLatch;

/**
 * @author 王楊帥
 * @create 2018-07-09 16:13
 * @desc
 **/
@Slf4j
public class Receiver {
    private CountDownLatch latch;
    @Autowired
    public Receiver(CountDownLatch latch) {
        this.latch = latch;
    }

    public void receiveMessage(String message) {
        log.info("Received <" + message + ">");
        latch.countDown();
    }


}
View Code

 

package cn.xiangxu.redis_pub_sub;

import cn.xiangxu.redis_pub_sub.domain.Receiver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
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;

@SpringBootApplication
@Slf4j
public class RedisPubSubApplication {

    /*
     * Redis消息監聽器容器
     * 這個容器加載了RedisConnectionFactory和消息監聽器
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("sprinboot-redis-messaage"));
        return container;
    }

    /*
     * 將Receiver注冊為一個消息監聽器,並指定消息接收的方法(receiveMessage)
     * 如果不指定消息接收的方法,消息監聽器會默認的尋找Receiver中的handleMessage這個方法作為消息接收的方法
     */
    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver){
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    /*
     * Receiver實例
     */
    @Bean
    Receiver receiver(CountDownLatch latch){
        return new Receiver(latch);
    }

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

    /*
     * Redis Template 用來發送消息
     */
    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory){
        return new StringRedisTemplate(connectionFactory);
    }

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(RedisPubSubApplication.class, args);

        StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
//      CountDownLatch latch = ctx.getBean(CountDownLatch.class);

        log.info("Sending message......");
        template.convertAndSend("sprinboot-redis-messaage", "Hello, SpringBoot redis message!!!!");
//      latch.wait();

//        System.exit(0);
    }
}
View Code

  3.3 效果測試

    3.3.1 利用redis服務器中的客戶端測試發布訂閱效果

    3.3.2 啟動springBoot項目

      在redis服務器中發布的消息會自動打印到控制台上

 

      

 

      

 

 

 

 

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM