springboot redis发布与订阅,同时和websocket相结合

备注:我们会在文章的最后把整个项目的git地址:传送门,以供参考

//代码地址
https://github.com/HouChenggong/redis_publish_websocket

1、maven集成websocket和redis

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
                <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>

2、Socket配置websocketConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/***
 * 配置ServerEndpointExporter,配置后会自动注册所有“@ServerEndpoint”注解声明的Websocket Endpoint
 */
@Configuration
public class WebSocketConfig {
   

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
   
        return new ServerEndpointExporter();
    }
}

3、RedisConfig配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class RedisConfig {
   

    @Bean("container")
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {
   

       RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) connectionFactory;
        //设置存储的节点
        lettuceConnectionFactory.setDatabase(0);
        container.setConnectionFactory(lettuceConnectionFactory);
        //这里要设定监听的主题是chat
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(RedisMessageListener receiver) {
   
        return new MessageListenerAdapter(receiver);
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
   
        return new StringRedisTemplate(connectionFactory);
    }
}

4、要实现的功能概述

4.1 实现websocket实时推送消息

4.2 实现redis发布与订阅

4.3 shiro不登陆也能访问websocket接口

 filterChainDefinitionMap.put("/socket/**", "anon");

4.4 通过静态HTML访问页面,页面在resource/static/html目录下

4.5 shiro不登录也能访问resource/static/html下的页面

   //socket测试入口
        filterChainDefinitionMap.put("/html/**", "anon");

4.6 实现websocket在线人数统计

4.7 实现websocket在线聊天,指定发送给全部的人,或者某一个人

4.8 给没有在线但是订阅主题的人推送消息


5、开始设计方案

5.1 首先写redis发布消息的service

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

@Service
public class SendMessageService {
   

    @Autowired
    private StringRedisTemplate template;

    /**
     * redis发布消息,就是往指定频道发消息
     *
     * @param channel 订阅的频道
     * @param message 发布 的内容
     */
    public void sendMessage(String channel, String message) {
   

        template.convertAndSend(channel, message);
        System.out.println</
  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Spring Boot中使用Redis进行发布订阅可以通过以下步骤实现: 1. 配置Redis连接信息 在application.properties文件中配置Redis连接信息,包括Redis的IP地址、端口号、密码等。 ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 2. 配置RedisTemplate 在Spring Boot中使用Redis需要使用到RedisTemplate,可以通过以下方式进行配置: ``` @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } ``` 上述代码中,我们配置了RedisTemplate的序列化方式,使用了StringRedisSerializer和GenericJackson2JsonRedisSerializer进行序列化。 3. 实现发布者 通过RedisTemplate实现发布者,可以使用convertAndSend方法进行消息发布。 ``` @Service public class RedisPublisher { @Autowired private RedisTemplate<String, Object> redisTemplate; public void publish(String channel, Object message) { redisTemplate.convertAndSend(channel, message); } } ``` 上述代码中,通过@Autowired注入了RedisTemplate,并实现了publish方法,通过convertAndSend方法实现了消息的发布。 4. 实现订阅者 通过@RedisListener注解实现订阅者,可以监听Redis中指定的频道,实现消息的订阅。 ``` @Service public class RedisSubscriber { @RedisListener(channel = "test") public void onMessage(Object message) { System.out.println("Received Message: " + message); } } ``` 上述代码中,通过@RedisListener注解指定了监听的频道,实现了onMessage方法,当Redis中有消息发布到该频道时,该方法会被回调。 5. 测试 在Spring Boot中测试Redis发布订阅可以通过以下方式: ``` @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired private RedisPublisher redisPublisher; @Test public void testPublish() { redisPublisher.publish("test", "Hello World!"); } } ``` 上述代码中,通过@Autowired注入了RedisPublisher,实现了testPublish方法,调用publish方法发布了一条消息到test频道中。 运行测试后,可以在RedisSubscriber的onMessage方法中看到收到了发布的消息。 以上就是Spring Boot中使用Redis进行发布订阅的详细步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值