springBoot +redis 消息订阅与发布

1.引入redis依赖

<!-- 集成redis依赖  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.创建RedisConfig

@Configuration 
public class RedisConfig {

	@Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 设置Key使用String序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
	
	@Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        // 添加订阅者监听类,数量不限.PatternTopic定义监听主题,这里监听test-topic主题
        container.addMessageListener(new SubscribeListener(), new PatternTopic("test-topic"));
        return container;
    }

}

3.订阅接收发布者的消息

public class SubscribeListener implements MessageListener {
    /**
     * 订阅接收发布者的消息
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 缓存消息是序列化的,需要反序列化。然而new String()可以反序列化,但静态方法valueOf()不可以
        System.out.println(new String(pattern) + "主题发布:" + new String(message.getBody()));
    }

}

4.发布消息

@Component
public class PublishService {
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 发布方法
     * @param channel 消息发布订阅 主题
     * @param message 消息信息
     * @throws IOException 
     * @throws ParseException 
     * @throws ClassNotFoundException 
     */
    public void publish(String channel, Object message) 
    								throws IOException, ParseException, ClassNotFoundException {
        // 该方法封装的 connection.publish(rawChannel, rawMessage);
		String timeStr1=LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		Date date = sdf.parse(timeStr1);
		
    	String userId = (String)StpUtil.getLoginId();
    	MessageTable messageTable = new MessageTable();
    	messageTable.setUserId(Integer.valueOf(userId));
    	messageTable.setMessage(String.valueOf(message));
    	messageTable.setCreationTime(date);
    	File file = new File("E:/messgaFile/"+(int)(Math.random()*32)+"/"+userId+".txt");
    	//判断文件夹是否存在
		if (!file.getParentFile().exists()) {
			//创建文件夹
		  file.getParentFile().mkdirs();
		}
		//判断文件是否存在
    	if(file.exists()){
    		//删除文件
    		file.delete();
    	}
    	//创建文件
    	file.createNewFile();
    	 //MessageTable对象序列化过程
    	FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(messageTable);
        oos.flush();
        oos.close();
        fos.close();
        
        //MessageTable对象反序列化过程
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        MessageTable st1 = (MessageTable) ois.readObject();
        ois.close();
        fis.close();
        
        redisTemplate.convertAndSend(channel, st1.getMessage());
    }
}

5.controller层

	@RequestMapping("/contextLoads")
	@ResponseBody
	public void contextLoads(HttpServletRequest request,HttpServletResponse response)
								throws ParseException, IOException, ClassNotFoundException{
		String channel = request.getParameter("channel");//如:test-topic
		String message = request.getParameter("message");
		service.publish(channel,message);
	}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值