SpringMVC集成Redis并作为简单的消息队列使用

一、SpringMVC集成Reids

Spring版本:4.3.2
jedis版本:2.9.0
commons-pool2版本:2.4.2
spring-data-commons版本:1.8.4.RELEASE
spring-data-redis版本:1.8.4.RELEASE

准备工作:在服务器上安装好Redis,如果服务器为CentOS可选择在线安装,参考:https://www.cnblogs.com/autohome7390/p/6433956.html

集成步骤如下:

1、创建redis.properties文件

# Redis Setting  
# Redis默认有16个库,序号是0-15,默认是选中的是0号数据库  
spring.redis.database=0  
# Redis服务器地址  
#spring.redis.host=117.50.42.49
spring.redis.host=117.50.42.49
# Redis服务器连接端口,默认是6379  
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)  
#spring.redis.password=lc123456
spring.redis.password=lc123456
# 连接池最大连接数(使用负值表示没有限制),根据实际情况修改  
spring.redis.pool.maxActive=8  
# 连接池最大阻塞等待时间(使用负值表示没有限制),根据实际情况修改  
spring.redis.pool.maxWait=-1  
# 连接池中的最大空闲连接,根据实际情况修改  
spring.redis.pool.maxIdle=8  
# 连接池中的最小空闲连接,根据实际情况修改  
spring.redis.pool.minIdle=0  
# 连接超时时间(毫秒),根据实际情况修改  
spring.redis.timeout=2000  

spring.redis.pool.testOnBorrow = false
spring.redis.pool.testOnReturn = false

2、创建spring-data-redis.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:redis="http://www.springframework.org/schema/redis" xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis-1.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  
  
    <!-- 载入redis.properties,这里要特别注意,如果有多个properties文件,必须用逗号分开,不能写成两个 <context:property-placeholder/> -->  
    <context:property-placeholder location="classpath*:/redis/redis.properties" ignore-unresolvable="true" />  
  
    <!-- 配置JedisPoolConfig相关参数 -->  
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxTotal" value="${spring.redis.pool.maxActive}"></property>
        <property name="maxIdle" value="${spring.redis.pool.maxIdle}"></property>  
        <property name="minIdle" value="${spring.redis.pool.minIdle}"></property>  
        <property name="maxWaitMillis" value="${spring.redis.pool.maxWait}"></property>
        <property name="testOnBorrow" value="${spring.redis.pool.testOnBorrow}"></property>  
        <property name="testOnReturn" value="${spring.redis.pool.testOnReturn}"></property>  
    </bean>  
  
    <!-- 配置redis服务器信息 -->
    <!-- Jedis ConnectionFactory 数据库连接配置,注意id名称必须为redisConnectionFactory-->  
    <bean id="redisConnectionFactory"  
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
        <property name="poolConfig" ref="poolConfig"></property>  
        <property name="hostName" value="${spring.redis.host}"></property>  
        <property name="port" value="${spring.redis.port}"></property>  
        <property name="password" value="${spring.redis.password}"></property>  
        <property name="database" value="${spring.redis.database}"></property>  
        <property name="timeout" value="${spring.redis.timeout}"></property>  
    </bean>  
  
    <!-- 配置RedisTemplate -->  
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
        <property name="connectionFactory" ref="redisConnectionFactory"></property>  
        <property name="keySerializer">  
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>  
        </property>  
        
        <property name="valueSerializer">  
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>  
        </property>  
        
        <property name="hashKeySerializer">  
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>  
        </property>  
        <!-- 使用JacksonJsonRedisSerializer需要引入jar包:barchart-wrap-jackson-1.8.6-build001.jar -->  
        <!-- JacksonJsonRedisSerializer 需要一个有参的构造函数,因此需要配置constructor-arg -->  
        <property name="hashValueSerializer">  
            <bean  
                class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer">  
                <constructor-arg type="java.lang.Class" value="java.lang.Object"></constructor-arg>  
            </bean>  
        </property>  
    </bean>  
  
    <!-- 配置redis连接池 -->  
    <bean class="redis.clients.jedis.JedisPool">  
        <constructor-arg ref="poolConfig" />  
        <constructor-arg value="${spring.redis.host}" />  
        <constructor-arg type="int" value="${spring.redis.port}" />  
        <constructor-arg type="int" value="${spring.redis.timeout}" />  
        <constructor-arg type="java.lang.String" value="${spring.redis.password}" />  
        <constructor-arg type="int" value="${spring.redis.database}" />  
    </bean>  
</beans> 

3、在spring-appliaction.xml中引入spring-data-redis.xml

<!-- 引入spring-data-redis.xml -->  
<import resource="../redis/spring-data-redis.xml"/>

4、项目启动错误说明

1)出现java.lang.NoClassDefFoundError:org/springframework/data/geo/Metric的异常一般是spring-data-commons, spring-data-redis, jedis 三个之间版本不兼容干的问题,一定要在网上查找相关资料找对Srping版本对应的jedis、spring-data-commons、spring-data-redis的版本。
2)出现java.lang.IllegalArgumentException: Could not resolve placeholder 'XXX' in string value "${XXX}";的原因是在Spring的配置文件中配置了多个<context:property-placeholder>标签,网上有对应的解决方法。可参考:https://blog.csdn.net/qq_39056805/article/details/80586672

5、Reids存储测试

在任意测试类中添加如下代码
1)声明变量

@Autowired
private RedisTemplate<String, Object> redisTemplate;

2)存入Redis数据库

redisTemplate.opsForValue().set("aaa", "bbb"); 

3) 执行之后用工具查看


image.png

二、添加消息监听,使用Redis完成消息的发布/订阅

1、编写消息发送类和消息监听类

1)消息发送类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class SendMessage {
    
     @Autowired
     private RedisTemplate<String, Object> redisTemplate;
     
     public void sendMessage(String channel, Serializable message) {
           redisTemplate.convertAndSend(channel, message);
      }
}

2)消息监听类

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.serializer.RedisSerializer;

public class ListenMessage implements MessageListener{
    
    @Autowired
    private RedisSerializer<Object> jsonRedisSerializer;
    

    @Override
    public void onMessage(Message message, byte[] pattern) {
        Object object =   jsonRedisSerializer.deserialize(message.getBody());
        System.out.println("onMessage:" + object.toString());
        
    }
}

2、在spring-data-redis.xml中添加配置

    <!--序列化-->
    <bean id="jdkSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />

    <!--消息监听处理类-->
    <bean id="messageDelegateListener" class="com.jy.common.redis.ListenMessage"/>

    <bean id="messageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
        <property name="delegate" ref="messageDelegateListener"/>
        <property name="serializer" ref="jdkSerializer" />
    </bean>

    <!--消息监听-->
    <redis:listener-container>
        <!--指定消息处理方法,序列化方式及主题名称-->
        <redis:listener ref="messageListener" method="handleMessage" serializer="jdkSerializer" topic="java"/>
    </redis:listener-container>

3、编写测试代码

1)声明变量

@Autowired
SendMessage sendMessage;

1)发送消息

for (int i = 0; i <100; i++) {
    sendMessage.sendMessage("channel-1",i);
}

3)查看打印日志

2019-12-13 17:19:54 -70213 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
2019-12-13 17:19:54 -70284 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
2019-12-13 17:19:54 -70287 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
onMessage:0
2019-12-13 17:19:54 -70310 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
onMessage:1
2019-12-13 17:19:54 -70311 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
onMessage:2
2019-12-13 17:19:54 -70336 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
2019-12-13 17:19:54 -70338 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
onMessage:3
2019-12-13 17:19:54 -70365 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
2019-12-13 17:19:54 -70368 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
onMessage:4
2019-12-13 17:19:54 -70392 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
2019-12-13 17:19:54 -70393 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
2019-12-13 17:19:54 -70415 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
onMessage:5
2019-12-13 17:19:54 -70418 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
onMessage:6
2019-12-13 17:19:54 -70442 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
2019-12-13 17:19:54 -70443 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
2019-12-13 17:19:55 -70466 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
onMessage:7
2019-12-13 17:19:55 -70467 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
2019-12-13 17:19:55 -70490 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
onMessage:8
2019-12-13 17:19:55 -70494 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
2019-12-13 17:19:55 -70518 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
onMessage:9
2019-12-13 17:19:55 -70520 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
2019-12-13 17:19:55 -70544 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
onMessage:10
2019-12-13 17:19:55 -70549 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
onMessage:11
2019-12-13 17:19:55 -70573 [http-bio-8080-exec-4] DEBUG   - Closing Redis Connection
2019-12-13 17:19:55 -70575 [http-bio-8080-exec-4] DEBUG   - Opening RedisConnection
onMessage:12
...
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容