ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

Spring boot+redis实现消息发布与订阅

2022-03-27 22:31:05  阅读:145  来源: 互联网

标签:return Spring boot redis private class new public redisTemplate


Spring boot+redis实现消息发布与订阅
https://blog.51cto.com/u_13501268/2489571

一.创建spring boot项目

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.41</version>
		</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

二.编辑yml配置文件

server:
  port: 7888
# 日志配置
logging:
  config: classpath:log/logback.xml
  level:
    cn.com.dhcc: info
    org.springframework: info
    org.springframework.web: info
    com.alibaba.nacos.client.naming: error
spring:
  redis:
     host: localhost
     port: 6379
     password: *********
     database: 1
     jedis:
      pool:
        max-idle: 8
        max-active: 8
        max-wait: -1
        min-idle: 0
     timeout: 5000
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

三.配置Redis

@Configuration
public class RedisConfiguration {
	/**
	 * 实例化 RedisTemplate 对象
	 *
	 * @return
	 */
	@Bean("RedisTemplateS")
	public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
		return redisTemplate;
	}
	/**
	 * 设置数据存入 redis 的序列化方式,并开启事务
	 * 
	 * @param redisTemplate
	 * @param factory
	 */
	private void initDomainRedisTemplate(@Qualifier("RedisTemplateS") RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
		// 如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to
		// String!
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());	
		FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<Object>(Object.class);
		redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
		redisTemplate.setValueSerializer(fastJsonRedisSerializer);
		//redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
		//redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		// 开启事务
		redisTemplate.setEnableTransactionSupport(true);
		redisTemplate.setConnectionFactory(factory);
	}
	/**
	 * 注入封装RedisTemplate @Title: redisUtil @return RedisUtil @date
	 * 
	 */
	@Bean(name = "redisUtils")
	public RedisUtils redisUtil(@Qualifier("RedisTemplateS") RedisTemplate<String, Object> redisTemplate) {
		RedisUtils redisUtil = new RedisUtils();
		redisUtil.setRedisTemplate(redisTemplate);
		return redisUtil;
	}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.

四.编写RedisUtil消息发布方法

public class RedisUtils {
	private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);
	private RedisTemplate<String, Object> redisTemplate;
	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	public void publish(String channal ,Object obj) {
		redisTemplate.convertAndSend(channal,obj );
	}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

五.配置消息监听

@Configuration
public class RedisMessageListener {
	/**
     * 创建连接工厂
     * @param connectionFactory
     * @param listenerAdapter
     * @return
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
      MessageListenerAdapter listenerAdapter,MessageListenerAdapter listenerAdapter2){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //接受消息的key
        container.addMessageListener(listenerAdapter,new PatternTopic("phone"));
        return container;
    }
    /**
     * 绑定消息监听者和接收监听的方法
     * @param receiver
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(ReceiverRedisMessage  receiver){
        return new MessageListenerAdapter(receiver,"receiveMessage");
    }
    /**
     * 注册订阅者
     * @param latch
     * @return
     */
    @Bean
    ReceiverRedisMessage receiver(CountDownLatch latch) {
        return new ReceiverRedisMessage(latch);
    }
    /**
     * 计数器,用来控制线程
     * @return
     */
    @Bean
    public CountDownLatch latch(){
        return new CountDownLatch(1);//指定了计数的次数 1
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.

六.消息订阅方法

public class ReceiverRedisMessage {
	private static final Logger log = LoggerFactory.getLogger(ReceiverRedisMessage.class);
	private CountDownLatch latch;
	@Autowired
	public ReceiverRedisMessage(CountDownLatch latch) {
		this.latch = latch;
	}
	/**
	 * 队列消息接收方法
	 *
	 * @param jsonMsg
	 */
	public void receiveMessage(String jsonMsg) {
		log.info("[开始消费REDIS消息队列phone数据...]");
		try {
			log.info("监听者收到消息:{}", jsonMsg);
			JSONObject exJson = JSONObject.parseObject(jsonMsg);
			User user = JSON.toJavaObject(exJson, User.class);
			System.out.println("转化为对象 :"+user);
			log.info("[消费REDIS消息队列phone数据成功.]");
		} catch (Exception e) {
			log.error("[消费REDIS消息队列phone数据失败,失败信息:{}]", e.getMessage());
		}
		latch.countDown();
	}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.

七.定时消息发布测试

@EnableScheduling
@Component
public class PublisherController {
	private static final Logger log = LoggerFactory.getLogger(PublisherController.class);
	@Autowired
	private RedisUtils redisUtils;
	@Scheduled(fixedRate = 5000)
	public String pubMsg() {
		User user=new User(1, "尚***", 26,"男","陕西省xxxx市xxxxxx县");
		redisUtils.publish("phone", user);
		log.info("Publisher sendes Topic... ");
		return "success";
	}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

八.测试结果
Spring boot+redis实现消息发布与订阅_redis发布与订阅

九.发布对象User实体

public class User implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int id;
	private String name;
	private int age;
	private String sex;
	private String address;
     .....................
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

标签:return,Spring,boot,redis,private,class,new,public,redisTemplate
来源: https://www.cnblogs.com/sunny3158/p/16064924.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有