Springboot21 整合redis、利用redis实现消息队列

Easter79
• 阅读 566

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根目录

Springboot21 整合redis、利用redis实现消息队列

        》执行 redis-server.exe

Springboot21 整合redis、利用redis实现消息队列

1.3.2 开启客户端

      进入到redis解压目录 -> 执行 redis-cli.exe

Springboot21 整合redis、利用redis实现消息队列

1.3.3 测试redis服务端和客户端的通信

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

Springboot21 整合redis、利用redis实现消息队列

1.3.4 关闭

      客户端和服务端都用 Ctrl + C 就可以关闭了

2 SpringBoot 集成 Redis

2.1 创建一个SpringBoot项目

    技巧01:创建时引入 spring-boot-starter-web 和 spring-boot-starter-data-redis

Springboot21 整合redis、利用redis实现消息队列 Springboot21 整合redis、利用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服务器进行相关的配置即可

Springboot21 整合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  对象进行操作即可

Springboot21 整合redis、利用redis实现消息队列 Springboot21 整合redis、利用redis实现消息队列

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 源代码

Springboot21 整合redis、利用redis实现消息队列 Springboot21 整合redis、利用redis实现消息队列

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

Springboot21 整合redis、利用redis实现消息队列 Springboot21 整合redis、利用redis实现消息队列

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服务器中的客户端测试发布订阅效果

Springboot21 整合redis、利用redis实现消息队列

3.3.2 启动springBoot项目

      在redis服务器中发布的消息会自动打印到控制台上

Springboot21 整合redis、利用redis实现消息队列

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Nginx + lua +[memcached,redis]
精品案例1、Nginxluamemcached,redis实现网站灰度发布2、分库分表/基于Leaf组件实现的全球唯一ID(非UUID)3、Redis独立数据监控,实现订单超时操作/MQ死信操作SelectPollEpollReactor模型4、分布式任务调试Quartz应用
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k