redis实现消息队列,点对点及发布订阅

解决redis序列化乱码问题

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.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }
}


1.点对点方式
 

    /**
     * 测试redis队列
     */
    @GetMapping("/senRedisMsgTest")
    public void senRedisMsgTest() {
        redisTemplate.opsForList().leftPush("username", "abcd");
        redisTemplate.opsForList().leftPush("username", "efgh");
        redisTemplate.opsForList().leftPush("username", "qwer");
        String username = String.valueOf(redisTemplate.opsForList().rightPop("username"));
        System.err.println(username);
    }

缺点是用rightPop()从redis队列中获取放入的元素时,只会按顺序拿出一条,如果是频繁写入,会存在无法全量拉取的问题

2.发布订阅模式

1.定义发布者

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

@Service
public class RedisPublisher {

    @Autowired
    private RedisTemplate<String, Object>  redisTemplate;

    public void publish(String channel, String message) {
        redisTemplate.convertAndSend(channel, message);
    }
}

2.发布者测试代码

@Autowired
private RedisPublisher redisPublisher;


@GetMapping("/publish")
public String publish() {
    redisPublisher.publish("user_channel", "testMsg");
    return "Message published!";
}

3.配置订阅者配置类

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.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class RedisSubscriberConfig {
    
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new ChannelTopic("user_channel"));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(RedisSubscriber receiver) {
        return new MessageListenerAdapter(receiver, "onMessage");
    }
}

4.订阅者接受处理消息

import org.springframework.stereotype.Component;

@Component
public class RedisSubscriber {

    public void onMessage(String message, String pattern) {
        System.err.println(message);
        System.err.println("Received <" + pattern + "> message: " + message);
    }
}

结果图:

发布订阅模式,在a服务写入时,b服务实时监听,进行处理,完美解决,需保证ab服务是同一个redis服务,且订阅者配置类中的channel和监听的方法名与发布者一致

RedisTemplate是Spring Data Redis提供的一个工具类,用于与Redis进行交互。它提供了一系列的方法来操作Redis的数据结构,包括发布订阅功能。 要使用RedisTemplate进行发布订阅,首先需要配置Redis的连接信息,并创建一个RedisTemplate实例。可以通过配置文件或者编程方式进行配置。以下是一个示例的配置文件: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 创建RedisTemplate实例的方式有多种,这里以常用的Java配置方式为例: ```java @Configuration public class RedisConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Bean public JedisConnectionFactory jedisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); config.setHostName(host); config.setPort(port); return new JedisConnectionFactory(config); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(jedisConnectionFactory()); template.setDefaultSerializer(new StringRedisSerializer()); template.setEnableDefaultSerializer(true); return template; } } ``` 接下来就可以使用RedisTemplate发布订阅消息了。Redis发布订阅模式使用了一对通道(channel)来进行消息的传递。发送方通过发布消息到指定的通道,接收方通过订阅该通道来接收消息。 以下是一个示例代码: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; public void publishMessage(String channel, String message) { redisTemplate.convertAndSend(channel, message); } public void subscribeChannel(String channel) { redisTemplate.execute(new RedisCallback<Object>() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.subscribe(new 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); } }, channel.getBytes()); return null; } }); } ``` 上述代码中,`publishMessage`方法用于发布消息到指定的通道,`subscribeChannel`方法用于订阅指定的通道并处理接收到的消息。 需要注意的是,Redis发布订阅模式是异步的,即发送方发布消息后并不会等待接收方处理,所以接收方需要单独开启一个线程或使用异步框架来处理接收到的消息。 希望以上信息对你有帮助!如果还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值