Spring boot 利用Redis实现队列消息监听简单示例

我的应用场景:当某个业务系统接收到MQ消息需要按照顺序进行执行时,且收到的消息间隔时间过短时,可以把需要执行的消息放到队列里面进行逐个消费,因为对消息执行的代码加锁是不行的,因为消息间隔时间小,容易出错,只能对消息再进行一层封装,然后执行.,这种情况只适用于消息不是必须实时消费。

1.Redis配置

主要配置序列化和反序列化使用的方式.

package com.example.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 集成Redis
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();

        redisTemplate.setConnectionFactory(factory);
        redisTemplate.afterPropertiesSet();
        setSerializer(redisTemplate);
        return redisTemplate;
    }

    private void setSerializer(RedisTemplate<String, String> template) {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
    }
}

2.按照存储Redis数据
这里面的value实际就是得到的消费消息.

@SpringBootTest
@RunWith(SpringRunner.class)
class DemoApplicationTests {
	private static final String key = "test007";

	@Autowired
	private RedisTemplate redisTemplate;

	@Test
	void contextLoads() {
		System.out.println(redisTemplate == null);
		redisTemplate.opsForList().leftPush(key , 12345);
		redisTemplate.opsForList().leftPush(key , 125678);
		Long size = redisTemplate.opsForList().size(key);
		System.out.println(size);

/*		Object object = redisTemplate.opsForList().rightPop(key);
		Object pop = redisTemplate.opsForList().rightPop(key);
		System.out.println(object);
		System.out.println(pop);
		Long temp = redisTemplate.opsForList().size(key);
		System.out.println(temp);*/

	}

}

监听器进行监听消费
定时器执行间隔,可以依照不同业务场景进行配置,用key的size进行判断redis是否存储了消费消息。因为是单线程,所以不会存在线程安全问题.
定时器执行需要在启动类加上@EnableScheduling注解.

@Component
@Slf4j
public class MyTask001 {
	
	//这里需要把key提取成常量, 因为存取需要同一个key
    private static final String key = "test007";
	
	//标识符,判断redis里面是否有消息.
    private static  Long keyNum = 0L;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 定时执行队列信息消费
     */
    @Scheduled(cron = "55 * * * * ?")
    public void testTask(){
        try {
            keyNum = redisTemplate.opsForList().size(key);
            while(keyNum > 0){
                Object object = redisTemplate.opsForList().rightPop(key);
                //执行的业务代码,单线程,因此不必对业务代码进行加锁.且是顺序执行.
                System.out.println(object);
                //再次获取标识符
                keyNum = redisTemplate.opsForList().size(key);
            }
        } catch (Exception e) {
            log.info("定时器异常信息,{}",e);
        }
    }

}

附录:
在这里插入图片描述

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring Boot中,你可以使用Redis作为消息队列实现消息的发布和订阅。下面是一个简单示例,演示如何在Spring Boot监听Redis消息队列: 首先,确保你的Spring Boot项目中已经配置了Redis的依赖。 创建一个消息监听器类,实现`MessageListener`接口,例如: ```java @Component public class RedisMessageListener implements MessageListener { @Override public void onMessage(Message message, byte[] pattern) { String channel = new String(message.getChannel()); String body = new String(message.getBody()); System.out.println("Received message: " + body + " from channel: " + channel); // 处理接收到的消息 } } ``` 接下来,创建一个配置类,配置Redis连接和消息监听器,例如: ```java @Configuration public class RedisConfig { @Bean JedisConnectionFactory jedisConnectionFactory() { RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(); configuration.setHostName("localhost"); configuration.setPort(6379); return new JedisConnectionFactory(configuration); } @Bean RedisMessageListenerContainer redisContainer() { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(jedisConnectionFactory()); container.addMessageListener(redisMessageListener(), new ChannelTopic("your-channel-name")); return container; } @Bean MessageListenerAdapter redisMessageListener() { return new MessageListenerAdapter(new RedisMessageListener()); } } ``` 在上面的配置中,你需要替换`localhost`和`6379`为你的Redis服务器的主机名和端口号,以及`your-channel-name`为你想要监听Redis频道名称。 最后,启动你的Spring Boot应用程序,当有消息发布到Redis的指定频道时,`RedisMessageListener`中的`onMessage`方法将会被调用,你可以在其中处理接收到的消息。 希望以上信息能帮助到你!如果你还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值