springboot整合redis的发布订阅模式

所谓发布订阅模式,就是发布了消息丢到通道中,消费者进行消费

看代码:

1  首先需要配置这个连接工厂  ,这地方可能有人有疑问,为什么需要单独做一个类呢,是由与这个连接工厂其他地方需要用到,所以以bean的方式注入

@Configuration
public class Redisconfig {
    @Value("${redis.database}")
    private int database;
    @Value("${redis.host}")
    private String hostName;
    @Value("${redis.port}")
    private int port;
    @Value("${redis.password}")
    private String password;


    @Bean(name = "redisConnectionFactory")
    protected RedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(hostName);
        redisStandaloneConfiguration.setPort(port);
        redisStandaloneConfiguration.setDatabase(database);
        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
        JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
        jedisClientConfiguration.connectTimeout(Duration.ofSeconds(60));// 60s
        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration.build());
    }
}

2 配置2 

/**
 * @program: operation->RedisTemplateConfig
 * @description:
 * @author: cxy
 * @create: 2019-12-26 17:55
 **/
@Configuration
public class RedisTemplateConfig {
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    @Bean
    public StringRedisTemplate redisTemplate() {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(redisConnectionFactory);
        return temple;
    }
    @Bean
    RedisMessageListenerContainer container(
                                            MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
//此处那个通道“cxy” 是监听者配置的通道,要与发送者相同 container.addMessageListener(listenerAdapter,
new PatternTopic("cxy")); return container; } //利用反射来创建监听到消息之后的执行方法 ,RedisReceiver 是接受者的类,receiveMessage接受者的方法
  @Bean MessageListenerAdapter listenerAdapter(RedisReceiver redisReceiver) { 


    return new MessageListenerAdapter(redisReceiver, "receiveMessage"); }
}

3RedisReceiver接受类

@Service
public class RedisReceiver {


    public void receiveMessage(String message) {
        //这里是收到通道的消息之后执行的方法
        System.out.println("message:"+message);
    }
}

4 发送的方法:

  @RequestMapping(value = "/q", method = RequestMethod.POST)
    public Result q() {
     redisTemplate.convertAndSend("cxy","我是中国人");
        return Result.success();
    }

5 主redis的配置:

redis:
  host: 
  password: 
  poolMaxIdle: 500
  poolMaxTotal: 1000
  poolMaxWait: 500
  port: 6379
  timeout: 10
  database: 0

6 调用结果:

springboot整合redis的发布订阅模式_第1张图片

 

 可以看到接受到了

你可能感兴趣的:(springboot整合redis的发布订阅模式)