SpringBoot中利用redis实现消息队列

最近在工作中遇到了需要消息队列功能,听说redis可以实现此功能,特意总结一下。

1.首先将redis配置好和引入maven jar包

  #redis 配置
  redis:
    #Redis数据库索引(默认为0)
    database: 0
    host: 10.168.2.160
    port: 6379
    lettuce:
      pool:
        max-active: 8   #最大连接数据库连接数,设 0 为没有限制
        max-idle: 8     #最大等待连接中的数量,设 0 为没有限制
        max-wait: -1ms  #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
        min-idle: 0     #最小等待连接中的数量,设 0 为没有限制
      shutdown-timeout: 100ms
      #password: auMartadmin@@  密码待定
		<!-- Redis -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

2.开始书写代码  消息的接收者

package com.pinemousecloudsevice.messagequeue;

import com.pinemousecloudsevice.common.constant.CommonConstant;
import com.pinemousecloudsevice.messagequeue.message.OrderInvoiceMessage;
import com.pinemousecloudsevice.task.service.AutoInvoiceStatusQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;



/**
 * 消息接收者实体类
 * @author 
 * @date 2021-03-18
 */
@Slf4j
@Component
public class RedisMessage implements MessageListener {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private AutoInvoiceStatusQueryService autoInvoiceStatusQueryService;

    /**
     *实际业务代码 消息体为对象实体
     */
//    @Override
//    public void onMessage(Message message, byte[] pattern) {
//        RedisSerializer<?> serializer = redisTemplate.getValueSerializer();
//        OrderInvoiceMessage orderInvoiceMessage = (OrderInvoiceMessage) serializer.deserialize(message.getBody());
//        //发票订单查询处理
//        Boolean isStop = autoInvoiceStatusQueryService.invoiceOrderQueryHandle(orderInvoiceMessage);
//        //不停止订单查询 加入redis list集合中
//        if(!isStop){
//            redisTemplate.opsForList().rightPush(CommonConstant.INVOICE_QUERY_STATUS_LIST, orderInvoiceMessage);
//        }
//    }

    /**
     * 测试代码
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
        String msg = serializer.deserialize(message.getBody());
        System.out.println("接收到的消息是:" + msg);
    }

}

3.配置消息订阅者

import com.pinemousecloudsevice.messagequeue.RedisMessage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;




/**
 * 消息队列  订阅者  redis配置
 * @author 
 * @date 2021-03-18
 */
@Configuration
public class RedisSubConfig {

    /**
     * 创建连接工厂
     *
     * @param connectionFactory
     * @param adapter
     * @return
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter adapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(adapter, new PatternTopic("topic"));
        return container;
    }

    /**
     * @param message
     * @return
     */
    @Bean
    public MessageListenerAdapter adapter(RedisMessage message){
        // onMessage 如果RedisMessage 中 没有实现接口,这个参数必须跟RedisMessage中的读取信息的方法名称一样
        return new MessageListenerAdapter(message, "onMessage");
    }
}

4.测试代码

@RestController
public class MsgController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/sendMsg")
    public String sendMsg(){
        stringRedisTemplate.convertAndSend("topic", "Hello world!");
        return "ok";
    }
}

其中 stringRedisTemplate也可替换为

@Resource
private RedisTemplate<String, Object> redisTemplate;
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java_wucao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值