美文网首页
SpringMVC集成Redis并作为简单的消息队列使用

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

作者: 程序猿加内特 | 来源:发表于2019-12-13 17:21 被阅读0次

    一、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
    ...
    

    相关文章

      网友评论

          本文标题:SpringMVC集成Redis并作为简单的消息队列使用

          本文链接:https://www.haomeiwen.com/subject/myofnctx.html