代码先锋网 代码片段及技术文章聚合

利用redis实现消息订阅和推送

redis的消息推送可以用在同一项目中,也可用在不同项目中,文章中我们以同一个项目为例:

首先我们需要一个maven 项目,

在pom文件中加入如下配置:


<!-- Redis 配置中心 -->
<profile.redis.ip>10.20.200.21</profile.redis.ip>
<profile.redis.port>6379</profile.redis.port>
<profile.redis.password>wangdai.com</profile.redis.password>
<profile.redis.timeout>15000</profile.redis.timeout>
<profile.redis.maxTotal>1000</profile.redis.maxTotal>
<profile.redis.usePool>true</profile.redis.usePool> <profile.redis.maxIdle>100</profile.redis.maxIdle>
<profile.redis.testOnBorrow>true</profile.redis.testOnBorrow>
<profile.redis.maxWaitMillis>2000</profile.redis.maxWaitMillis>

对应在conf中新建redis.properties文件:

redis.hostName=${profile.redis.ip}
redis.passWord=${profile.redis.password}
redis.port=${profile.redis.port}
redis.timeout=${profile.redis.timeout}
redis.usePool=${profile.redis.usePool}
redis.maxIdle=6
redis.minEvictableIdleTimeMillis=300000
redis.numTestsPerEvictionRun=3
redis.timeBetweenEvictionRunsMillis=60000
redis.maxIdle=${profile.redis.maxIdle}
redis.maxTotal=${profile.redis.maxTotal}
redis.maxWaitMillis=${profile.redis.maxWaitMillis}
redis.testOnBorrow=${profile.redis.testOnBorrow}

在applicationContext.xml 中加入相关配置

	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:conf/jdbc.properties</value>
				<value>classpath:conf/dubbo.properties</value>
				<value>classpath:conf/redis.properties</value>
			</list>
		</property>
	</bean>

新建一个application-redis.xml 的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
	xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:redis="http://www.springframework.org/schema/redis"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
						   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
						   http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis-1.0.xsd">

	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="${redis.maxTotal}" />
		<property name="maxIdle" value="${redis.maxIdle}" />
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
	</bean>
	<bean id="jdkSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />  

	<bean  id='jedisConnectionFactory' class='org.springframework.data.redis.connection.jedis.JedisConnectionFactory' >
	  <property name="hostName" value="${redis.hostName}"></property>
	  <property name="port" value="${redis.port}"></property>
	  <property name="usePool" value="${redis.usePool}"></property>
	  <property name="password" value="${redis.passWord}"/>
	  <property name="poolConfig" ref="jedisPoolConfig"></property> 
	</bean>
       
     <bean id='redisTemplate' class='org.springframework.data.redis.core.RedisTemplate'>  
         <property name="connectionFactory" ref="jedisConnectionFactory"></property>
        <!-- 使用string主要是key 在redis端用命令好读 不然默认的序列化没办法读 -->    
        <property name="keySerializer">    
           <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />    
        </property>    
        <property name="hashKeySerializer">    
           <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />    
        </property>  
        <property name="valueSerializer">  
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
        </property>
     </bean>
	
 	
	 redis发布订阅配置
   <bean id="serialization" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />  
   
  消息监听适配器  delegate属性指定真正的目标处理器  
    <bean id="smsMessageListener"
        class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
        <property name="delegate" ref="tQMessageDelegateListener" />
        <property name="serializer" ref="serialization" />  
    </bean>
    <bean id="tQMessageDelegateListener" class="com.hz.hzdjr.controller.TQMessageDelegateListener"/>
    消息监听适配器对应的监听容器
     <redis:listener-container  connection-factory="jedisConnectionFactory">
        <redis:listener ref="smsMessageListener" method="handleMessage"
            topic="test" /> 
    </redis:listener-container>
	
	
	
	
</beans>

application-redis.xml 中配置消息发送者的信息 和 监听者的信息。

我们需要创建一个监听处理类:TQMessageDelegateListener

package com.hz.hzdjr.controller;

public class TQMessageDelegateListener  {

    public void  handleMessage(String message){
	
    	System.out.println("监听到的消息为:"+message);
	
	}
}

我们需要创建一个消息发送方的服务:

RedisService:

package com.hz.hzdjr.system.service;

public interface RedisService {
	/*
	 * 设置频道
	 */
	public static final String TQCHANNEL = "channel_message";
	public void sendMessage(String channel, String message);
}

RedisServiceImpl:

package com.hz.hzdjr.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.hz.hzdjr.system.service.RedisService;

@Service
public class RedisServiceImpl implements RedisService {
	@Autowired
	public RedisTemplate<String, Object> redisTemplate;
	@Override
	public void sendMessage(String channel, String message) {
	System.out.println("开始发布消息。。。");
	redisTemplate.convertAndSend(channel, message); 
	System.out.println("发布成功!");
	}
}

此时我们的准备工作就结束了。

我们只需要启动项目后调用redisService.sendMessage();方法发送消息,那么

handleMessage监听方法将会被执行。

注意:消息发送方的channel  必须和监听方的一样。





版权声明:本文为xj15010735572原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xj15010735572/article/details/80404364

智能推荐

消息订阅与推送

写在前面:消息订阅与推送都通过nsq的tcp服务实现。 关于消息的推送最重要的是两个文件:nsqd/protocol_v2.go和nsqd/client_v2.go。 当一个客户端与nsqd进程建立了一个tcp连接时,会调用protocolV2.IOLoop方法,并新建一个clientV2结构体对象。IOLoop方法会启动一个协程执行messagePump方法。并且对于每一个tcp连接,都会有两个...

使用Redis订阅+Websocket 将消息推送给前端

前言         首先说一下业务,我们的webapi需要从redis订阅消息,并把订阅到的消息推送给web前端。要求不同的用户建立不同的websocket连接,并把websocket要把消息分发给不同的用户。 Redis的消息订阅与发布并不复杂,这里不再赘述。主要讲解如何通过webSocke将消息推送给前端。 我们...

Redis实现消息队列(2)——通过spring-boot-starter-data-redis发布和订阅消息

1.引入jar包 2.  RedisUtils工具类 3. 发布消息 4.  注册订阅通道 5.  实现订阅接口  ...

vue-websocket-emqtt vue通过websocket连接emqtt实现消息订阅和推送

简介 近年来随着 Web 前端的快速发展,浏览器新特性层出不穷,越来越多的应用可以在浏览器端或通过浏览器渲染引擎实现,Web 应用的即时通信方式 WebSocket 得到了广泛的应用。 WebSocket 是一种在单个 TCP 连接上进行全双工通讯的协议。WebSocket 通信协议于2011年被 IETF 定为标准 RFC 6455,并由 RFC 7936 补充规范。WebSocket API ...

Redis实现消息队列(1)——通过Jedis发布和订阅消息

 1.  引入jar  2. JedisUtils工具类 3.发布消息 4. 订阅消息  ...

猜你喜欢

java实现Redis消息发布订阅

Redis发布订阅架构 Redis提供了发布订阅功能,可以用于消息的传输,Redis的发布订阅机制包括三个部分,发布者,订阅者和Channel。 发布者和订阅者都是Redis客户端,Channel则为Redis服务器端,发布者将消息发送到某个的频道,订阅了这个频道的订阅者就能接收到这条消息。Redis的这种发布订阅机制与基于主题的发布订阅类似,Channel相当于主题。 Redis发布订阅功能 (...

SpringBoot整合Redis实现消息发布订阅

前言: SpringBoot整合Redis此处不作赘述 为减少篇幅,只有部分代码(不影响使用) 本文基于lombok插件以及logback日志,所以如果某些注解报错或者无法导入基本是这两处的问题 勿喷 正文 Redis常量配置(个人习惯,本类按需求而定) 配置消息处理器 上述为消息处理器,目前无用。需要后面配置,PushUtil为个人封装的个推消息推送工具类,可以删除,根据自己逻辑决定相关操作。 ...

基于springboot实现简单redis订阅消息

基于springboot实现简单redis订阅消息 配置 消息处理 pom...

Java SpringBoot实现Redis 消息订阅处理

Redis 消息订阅处理可以结合 Redis缓存 一起使用。原理是Redis订阅了消息通道后,可以通过发送消息,Redis接收消息并进行业务处理 使用详解: 1. RedisCofig 类 2. 新建一个消息接收类 MessageReceiver 3. 核心实现代码...

springboot整合redis实现消息发布订阅

springboot整合redis实现消息发布和订阅 先了解一下redis消息发布订阅的机制: 发布者将消息发布在一个channel(可认为是频道)上,可以供多个订阅者订阅查看信息,所以说channel是连接发布者和订阅者之间的桥梁。 1.实现一个用于接听消息的实体类 此处可用@Component注解标识 ,也可以在Configration文件中用@Bean注入。 2.进行redis消息监听器和适...