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

摘要:
1前提准备  1.1创建一个springboot项目技巧01:本博文基于springboot2.0创建  1.2安装redis    1.2.1linux版本参考博文    1.2.2windows版本到redis官网下载windows版本的压缩包后,解压即可  1.3redis使用本博文以window版本为例子,linux版本请参见    1.3.1开启服务端》进入到解压后的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根目录

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

》执行redis-server.exe

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

    1.3.2 开启客户端

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

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

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

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

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

    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服务器进行相关的配置即可

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

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

packagecn.xiangxu.redis_pub_sub.web;
importlombok.extern.slf4j.Slf4j;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.data.redis.core.RedisTemplate;
importorg.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public classTestControllerTest {
    /**
     * 依赖注入RedisTemplate,直接利用RedisTemplate操作redis即可
     */
    @Autowired
    private RedisTemplate<String, String>redisTemplate;
    @Test
    public voidtest01(){
        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 源代码

packagecn.xiangxu.redis_pub_sub.domain;
importlombok.extern.slf4j.Slf4j;
importorg.springframework.beans.factory.annotation.Autowired;
importjava.util.concurrent.CountDownLatch;
/**
 * @author王杨帅
 * @create 2018-07-09 16:13
 * @desc
 **/
@Slf4j
public classReceiver {
    privateCountDownLatch latch;
    @Autowired
    publicReceiver(CountDownLatch latch) {
        this.latch =latch;
    }
    public voidreceiveMessage(String message) {
        log.info("Received <" + message + ">");
        latch.countDown();
    }
}
View Code
packagecn.xiangxu.redis_pub_sub;
importcn.xiangxu.redis_pub_sub.domain.Receiver;
importlombok.extern.slf4j.Slf4j;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.annotation.Bean;
importorg.springframework.data.redis.connection.RedisConnectionFactory;
importorg.springframework.data.redis.core.StringRedisTemplate;
importorg.springframework.data.redis.listener.PatternTopic;
importorg.springframework.data.redis.listener.RedisMessageListenerContainer;
importorg.springframework.data.redis.listener.adapter.MessageListenerAdapter;
importjava.util.concurrent.CountDownLatch;
@SpringBootApplication
@Slf4j
public classRedisPubSubApplication {
    /*
     * Redis消息监听器容器
     * 这个容器加载了RedisConnectionFactory和消息监听器
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter){
        RedisMessageListenerContainer container = newRedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("sprinboot-redis-messaage"));
        returncontainer;
    }
    /*
     * 将Receiver注册为一个消息监听器,并指定消息接收的方法(receiveMessage)
     * 如果不指定消息接收的方法,消息监听器会默认的寻找Receiver中的handleMessage这个方法作为消息接收的方法
     */
    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver){
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
    /*
     * Receiver实例
     */
    @Bean
    Receiver receiver(CountDownLatch latch){
        return newReceiver(latch);
    }
    @Bean
    CountDownLatch latch(){
        return new CountDownLatch(1);
    }
    /*
     * Redis Template 用来发送消息
     */
    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory){
        return newStringRedisTemplate(connectionFactory);
    }
    public static voidmain(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实现消息队列第6张

    3.3.2 启动springBoot项目

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

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

免责声明:文章转载自《Springboot21 整合redis、利用redis实现消息队列》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Oracle12.2c统一审计(unified auditing)六问几种数据交换格式下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

redis的incr和incrby命令

Redis Incr 命令将 key 中储存的数字值增一,如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。 Redis Incrby 命令将 key 中储存的数字加上指定的增量值,如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。 Redis Hincrby 命令用于为哈希...

Redis打造URL缩短服务

用Redis打造URL缩短服务 此文章的英文版本已首发于 CodeProject :Building a simple URL shorten service with Redis 阅读文章之前,我建议你先下载源码,一边看文章,一边看代码。 代码在这里下载:http://www.codeproject.com/KB/NoSQL/819235/MicroU...

RedisTemplate访问Redis数据结构(四)——Set

Redis的Set是string类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据,Redis 中 集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。 SetOperations提供了对无序集合的一系列操作。首先初始化spring工厂获得redisTemplate和opsForSet private RedisTempl...

Redis事务、持久化、发布订阅

一、Redis事物 1. 概念 Redis 事务可以一次执行多个命令, 并且带有以下两个重要的保证: 事务是一个单独的隔离操作:事务中的所有命令都会序列化、按顺序地执行。事务在执行的过程中,不会被其他客户端发送来的命令请求所打断。 事务是一个原子操作:事务中的命令要么全部被执行,要么全部都不执行。 一个事务从开始到执行会经历以下三个阶段: 开始事务。 命...

【PHP】你使用过redis做异步队列么,是怎么用的?有什么缺点?

Redis设计主要是用来做缓存的,但是由于它自身的某种特性使得它可以用来做消息队列。 它有几个阻塞式的API可以使用,正是这些阻塞式的API让其有能力做消息队列; 另外,做消息队列的其他特性例如FIFO(先入先出)也很容易实现,只需要一个list对象从头取数据,从尾部塞数据即可; Redis能做消息队列还得益于其list对象blpop brpop接口以及P...

centos安装redis并开启多个redis实例

1.下载安装包       下载地址 :  http://download.redis.io/releases/,去里面找对应的版本下载        例如  wget http://download.redis.io/releases/redis-5.0.0.tar.gz 2.解压       tar -zxf  redis-5.0.0.tar.gz  ...