文章详情

短信预约信息系统项目管理师 报名、考试、查分时间动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Spring boot+redis实现消息发布与订阅

2017-09-29 09:37

关注

Spring boot+redis实现消息发布与订阅

一.创建spring boot项目

<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.41version>
        dependency>

二.编辑yml配置文件

server:
  port: 7888
# 日志配置
logging:
  config: classpath:log/logback.xml
  level:
    cn.com.dhcc: info
    org.springframework: info
    org.springframework.web: info
    com.alibaba.nacos.client.naming: error
spring:
  redis:
     host: localhost
     port: 6379
     password: *********
     database: 1
     jedis:
      pool:
        max-idle: 8
        max-active: 8
        max-wait: -1
        min-idle: 0
     timeout: 5000

三.配置Redis

@Configuration
public class RedisConfiguration {

    
    @Bean("RedisTemplateS")
    public RedisTemplate functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }

    
    private void initDomainRedisTemplate(@Qualifier("RedisTemplateS") RedisTemplate redisTemplate, RedisConnectionFactory factory) {
        // 如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can"t cast to
        // String!
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        //redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 开启事务
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.setConnectionFactory(factory);
    }

    
    @Bean(name = "redisUtils")
    public RedisUtils redisUtil(@Qualifier("RedisTemplateS") RedisTemplate redisTemplate) {
        RedisUtils redisUtil = new RedisUtils();
        redisUtil.setRedisTemplate(redisTemplate);
        return redisUtil;
    }

四.编写RedisUtil消息发布方法

public class RedisUtils {
    private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);

    private RedisTemplate redisTemplate;

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void publish(String channal ,Object obj) {
        redisTemplate.convertAndSend(channal,obj );
    }
}

五.配置消息监听

@Configuration
public class RedisMessageListener {

    
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter listenerAdapter,MessageListenerAdapter listenerAdapter2){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //接受消息的key
        container.addMessageListener(listenerAdapter,new PatternTopic("phone"));
        return container;
    }

    
    @Bean
    public MessageListenerAdapter listenerAdapter(ReceiverRedisMessage  receiver){
        return new MessageListenerAdapter(receiver,"receiveMessage");
    }

    
    @Bean
    ReceiverRedisMessage receiver(CountDownLatch latch) {
        return new ReceiverRedisMessage(latch);
    }

    
    @Bean
    public CountDownLatch latch(){
        return new CountDownLatch(1);//指定了计数的次数 1
    }
}

六.消息订阅方法

public class ReceiverRedisMessage {

    private static final Logger log = LoggerFactory.getLogger(ReceiverRedisMessage.class);
    private CountDownLatch latch;

    @Autowired
    public ReceiverRedisMessage(CountDownLatch latch) {
        this.latch = latch;
    }

    
    public void receiveMessage(String jsonMsg) {
        log.info("[开始消费REDIS消息队列phone数据...]");
        try {
            log.info("监听者收到消息:{}", jsonMsg);
            JSONObject exJson = JSONObject.parseObject(jsonMsg);
            User user = JSON.toJavaObject(exJson, User.class);
            System.out.println("转化为对象 :"+user);
            log.info("[消费REDIS消息队列phone数据成功.]");
        } catch (Exception e) {
            log.error("[消费REDIS消息队列phone数据失败,失败信息:{}]", e.getMessage());
        }
        latch.countDown();
    }
}

七.定时消息发布测试

@EnableScheduling
@Component
public class PublisherController {

    private static final Logger log = LoggerFactory.getLogger(PublisherController.class);

    @Autowired
    private RedisUtils redisUtils;

    @Scheduled(fixedRate = 5000)
    public String pubMsg() {
        User user=new User(1, "尚***", 26,"男","陕西省xxxx市xxxxxx县");
        redisUtils.publish("phone", user);
        log.info("Publisher sendes Topic... ");
        return "success";
    }
}

八.测试结果
Spring boot+redis实现消息发布与订阅

九.发布对象User实体

public class User implements Serializable {

    
    private static final long serialVersionUID = 1L;
    private int id;
    private String name;
    private int age;
    private String sex;
    private String address;
     .....................
}

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 资料下载
  • 历年真题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容
咦!没有更多了?去看看其它编程学习网 内容吧