前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springmvc+redis实现简单消息队列

springmvc+redis实现简单消息队列

作者头像
有一只柴犬
发布2024-01-25 10:50:13
1280
发布2024-01-25 10:50:13
举报
文章被收录于专栏:JAVA体系

1、springmvc-redis.xml配置:

代码语言:javascript
复制
<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation=" 
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
  
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxIdle" value="${redis.maxIdle}" />  
        <property name="maxTotal" value="${redis.maxActive}" />  
        <property name="MaxWaitMillis" value="${redis.maxWait}" />  
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
    </bean>  
      
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
        p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"  p:pool-config-ref="poolConfig">
     </bean>

    <!-- redis客户端模板 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <!-- 注入连接工厂 -->
        <property name="connectionFactory" ref="connectionFactory" />
        <!-- 配置key序列化类 -->
        <property name="keySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <!-- 配置value序列化类 -->
        <property name="valueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
    </bean>


    <!-- 定义监听容器 -->
    <bean id="redisMessageListenerContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer" destroy-method="destroy">
        <property name="connectionFactory" ref="connectionFactory"/>
        <!-- 任务执行器 -->
        <property name="taskExecutor">
            <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
                <property name="poolSize" value="10"/>
            </bean>
        </property>
        <!-- 消息监听器 -->
        <property name="messageListeners">
            <map>
                <entry key-ref="redisSubscribeDaoImpl">
                    <list>
                        <!-- 监听通道匹配 -->
                        <bean class="org.springframework.data.redis.listener.PatternTopic">
                            <constructor-arg value="channel*" />
                        </bean>
                    </list>
                </entry>
            </map>
        </property>
    </bean>
</beans>

2、生产者:

代码语言:javascript
复制
package com.yllt.site.redis.impl;

import com.yllt.site.redis.IRedisPublishDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

/**
 *
 * @author asus
 * @date 2019/8/17
 */
@Repository
public class RedisPublishDaoImpl implements IRedisPublishDao {

    private static Logger logger = LoggerFactory.getLogger(RedisPublishDaoImpl.class);


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    static String[] channels = null;
    static {
        if(channels == null){
            channels = new String[]{"channel1", "channel2", "channel3", "channel4", "channel5"};
        }
    }

    @Override
    public void publishMessage(String message) {
        logger.info("消息发布开始..." + message);
        redisTemplate.convertAndSend("channel1", message);
    }
}

3、消费者:

代码语言:javascript
复制
package com.yllt.site.redis.impl;

import com.alibaba.fastjson.JSONObject;
import com.yllt.common.util.CollectionUtil;
import com.yllt.site.domain.Camera;
import com.yllt.site.domain.Trajectory;
import com.yllt.site.service.ICameraService;
import com.yllt.site.service.ITrajectoryService;
import com.yllt.site.util.LatLngUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息订阅者
 * @author asus
 * @date 2019/8/17
 */
@Service("redisSubscribeDaoImpl")
public class RedisSubscribeDaoImpl implements MessageListener {

    private static Logger logger = LoggerFactory.getLogger(RedisSubscribeDaoImpl.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {

        logger.info("消息订阅开始...");
        byte[] body = message.getBody();
        String msgBody = (String) redisTemplate.getValueSerializer().deserialize(body);
        logger.info("接收到消息内容:{}" + msgBody);

        

    }


}

4、测试:

代码语言:javascript
复制
String json = JSONObject.toJSONString(xxx);
redisPublishDao.publishMessage(json);
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-01-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis®
腾讯云数据库 Redis®(TencentDB for Redis®)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档