Redis实现消息的发布和订阅

Redis实现消息的发布和订阅

1、在springboot项目的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>spring-boot-redis-message</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-redis-message</name>
    <description>spring-boot-redis-message</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、在application.properties中配置redis参数

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=10
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000ms

3、redis的配置类

package com.example.springbootredismessage.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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;

import java.net.UnknownHostException;

/**
 * @author zhangshixing
 * @date 2021年11月06日 9:44
 * redis 配置类
 */
@Configuration
public class RedisConfig {

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(redisConnectionFactory);
        StringRedisSerializer stringSerial = new StringRedisSerializer();
        // redis key 序列化方式使用stringSerial
        template.setKeySerializer(stringSerial);
        // redis value 序列化方式使用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // redis hash key 序列化方式使用stringSerial
        template.setHashKeySerializer(stringSerial);
        // redis hash value 序列化方式使用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

4、redis消息发布和监听

4.1 发送消息

package com.example.springbootredismessage.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author zhangshixing
 * @date 2021年11月07日 11:18
 */
@RestController
@RequestMapping(value = "rest/redis")
public class RedisSendMessageController {

    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "send/message", method = RequestMethod.GET)
    public void testPush(@RequestParam("body") String body) {
        /**
         * 使用redisTemplate的convertAndSend()函数,
         * String channel, Object message
         * channel代表管道,
         * message代表发送的信息
         */
        redisTemplate.convertAndSend("test_topic", body);
        System.out.println("发送消息成功,channel:test_topic , messgae:" + body);
    }
}

4.2 接收消息

package com.example.springbootredismessage.config;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @author zhangshixing
 * @date 2021年11月07日 11:22
 * redis订阅方:接收消息
 * 为了接收 Redis 渠道发送过来的消息,我们先定义一个消息监听器( MessageListener )
 */
@Component
public class MyRedisSubscribeListener implements MessageListener {
    /**
     * 这里的 onMessage 方法是得到消息后的处理方法, 其中 message 参数代表 Redis 发送过来的消息,
     * pattern是渠道名称,onMessage方法里打印了它们的内容。这里因为标注了@Component注解,所以
     * 在Spring Boot扫描后,会把它自动装配到IoC容器中 ,监听着对象RedisMessageListener会自动
     * 将消息进行转换。
     *
     * @param message
     * @param bytes
     */
    @Override
    public void onMessage(Message message, byte[] bytes) {
        System.out.println("接收消息!");
        //消息体
        String body = null;
        try {
            //解决string乱码
            body = new String(message.getBody(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //渠道名称
        String topic = new String(bytes);
        System.out.println("消息体:" + body);
        System.out.println("渠道名称:" + topic);
    }
}

5、启动类

package com.example.springbootredismessage;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootRedisMessageApplication {

	public static void main(String[] args) {

		SpringApplication.run(SpringBootRedisMessageApplication.class, args);
	}

}

6、测试

http://localhost:8080/rest/redis/send/message?body=helloworld
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 RedisTemplate 实现发布订阅消息,具体实现可以参考以下代码: 1. 配置 RedisTemplate ``` @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } ``` 2. 发布消息 ``` @Autowired private RedisTemplate<String, Object> redisTemplate; public void publish(String channel, Object message) { redisTemplate.convertAndSend(channel, message); } ``` 3. 订阅消息 ``` @Component public class RedisMessageSubscriber implements MessageListener { @Override public void onMessage(Message message, byte[] bytes) { String channel = new String(message.getChannel()); Object messageBody = redisTemplate.getValueSerializer().deserialize(message.getBody()); // 处理消息 } @Autowired private RedisTemplate<String, Object> redisTemplate; @PostConstruct public void subscribe() { redisTemplate.execute((RedisCallback<Void>) connection -> { connection.subscribe(this::onMessage, "channel1".getBytes()); return null; }); } } ``` 以上代码实现了一个简单的发布订阅消息功能,可以根据实际需求进行修改和扩展。 ### 回答2: Spring Boot是一个基于Java的开源框架,它提供了快速构建应用程序的能力。Redis是一个高性能的键值对存储数据库,可以用于缓存、消息队列等场景。 在Spring Boot中整合Redis实现发布订阅消息可以使用Redisson这个开源框架。下面是一个示例: 首先,在pom.xml文件中添加Redisson的依赖: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.15.1</version> </dependency> ``` 然后,在application.properties文件中配置Redis连接信息: ```properties spring.redis.host=localhost spring.redis.port=6379 ``` 接下来,创建一个消息发布者: ```java @Component public class MessagePublisher { @Autowired private RedissonClient redissonClient; public void publishMessage(String channel, String message) { RTopic<String> topic = redissonClient.getTopic(channel); topic.publish(message); } } ``` 再创建一个消息订阅者: ```java @Component public class MessageSubscriber { @PostConstruct public void subscribeMessages() { RPatternTopic<String> topic = redissonClient.getPatternTopic("messages.*"); topic.addListener(new PatternMessageListener<String>() { @Override public void onMessage(CharSequence pattern, CharSequence channel, String message) { // 处理消息 System.out.println("Received message: " + message); } }); } } ``` 最后,在需要发布消息的地方调用发布者的publishMessage方法即可: ```java @Autowired private MessagePublisher messagePublisher; public void sendMessage() { messagePublisher.publishMessage("messages.test", "Hello, Redis!"); } ``` 以上是一个简单的Spring Boot整合Redis实现发布订阅消息的例子。通过配置Redis连接信息和使用Redisson框架,可以方便地实现消息发布订阅的功能。 ### 回答3: Spring Boot整合Redis实现发布订阅消息的例子非常简单。首先,我们需要在pom.xml文件中添加RedisSpring Boot依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,在application.properties文件中配置Redis的连接信息: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 然后,我们创建一个消息发布者和一个消息订阅者的类。发布者负责发布消息订阅者负责接收并处理消息发布者的示例代码如下: ``` @Component public class MessagePublisher { @Autowired private RedisTemplate<String, Object> redisTemplate; public void publish(String channel, String message) { redisTemplate.convertAndSend(channel, message); } } ``` 订阅者的示例代码如下: ``` @Component public class MessageSubscriber { @Autowired private RedisTemplate<String, Object> redisTemplate; private CountDownLatch latch; public MessageSubscriber(CountDownLatch latch) { this.latch = latch; } public void receiveMessage(String message) { System.out.println("Received message: " + message); latch.countDown(); } @Bean public MessageListenerAdapter messageListener() { return new MessageListenerAdapter(this); } @Bean public RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory, MessageListenerAdapter messageListener) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(messageListener, new PatternTopic("channel")); // 替换为实际的频道名称 return container; } } ``` 最后,我们创建一个包含main方法的启动类,并在该类中注入发布者和订阅者的实例,并进行消息发布订阅的测试: ``` @SpringBootApplication public class RedisPubSubExampleApplication { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(RedisPubSubExampleApplication.class, args); MessagePublisher publisher = ctx.getBean(MessagePublisher.class); publisher.publish("channel", "This is a test message"); CountDownLatch latch = ctx.getBean(CountDownLatch.class); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } } ``` 以上就是使用Spring Boot整合Redis实现发布订阅消息的例子。通过简单的配置和几行代码,我们就可以实现消息发布订阅功能。需要注意的是,这只是一个简单的示例,实际应用中可能需要更多的配置和处理逻辑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值