搜索
首页数据库Redisredis的发布订阅功能

redis的发布订阅功能

Sep 27, 2019 am 09:22 AM
redis

redis提供了简单的发布订阅功能,对于一些合适的场景(比如不要求消费者不在线时也能收到离线消息),比起专业的MQ来说,用起来更简单些。本文主要是记录下怎么在SpringBoot里头使用redis的发布订阅功能。

定义生产者

配置

@Bean
    MyPublisher redisPublisher(RedisConnectionFactory factory) {
        return new MyPublisher( redisTemplate(factory), topic() );
    }
    @Bean
    ChannelTopic topic() {
        return new ChannelTopic( "pubsub:queue" );
    }

生产者实例

public class MyPublisher {
    private final RedisTemplate< String, Object > template;
    private final ChannelTopic topic;
    private final AtomicLong counter = new AtomicLong( 0 );
    public MyPublisher( final RedisTemplate< String, Object > template,
                               final ChannelTopic topic ) {
        this.template = template;
        this.topic = topic;
    }
    @Scheduled( fixedDelay = 100 )
    public void publish() {
        template.convertAndSend( topic.getTopic(), "Message " + counter.incrementAndGet() +
                ", " + Thread.currentThread().getName() );
    }
}

定义消费者

配置

//subscribe
    @Bean
    MessageListenerAdapter messageListener() {
        return new MessageListenerAdapter( new MyMessageListener() );
    }
    @Bean
    RedisMessageListenerContainer redisContainer(RedisConnectionFactory factory) {
        final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        container.addMessageListener(messageListener(), topic());
        return container;
    }

消费者实例

public class MyMessageListener implements MessageListener {
    @Override
    public void onMessage( final Message message, final byte[] pattern ) {
        System.out.println( "Message received: " + message.toString() );
    }
}

运行

  .   ____          _            __ _ _
 /\\ / ___&#39;_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | &#39;_ | &#39;_| | &#39;_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  &#39;  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.2.RELEASE)
2016-02-16 00:14:08.190  INFO 1481 --- [           main] com.codecraft.RedisdemoApplication      : Starting RedisdemoApplication on Jupiter.local with PID 1481 (/Users/codecraft/workspace/redisdemo/target/classes started by codecraft in /Users/codecraft/workspace/redisdemo)
2016-02-16 00:14:08.193  INFO 1481 --- [           main] com.codecraft.RedisdemoApplication      : No active profile set, falling back to default profiles: default
2016-02-16 00:14:08.242  INFO 1481 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@140e5a13: startup date [Tue Feb 16 00:14:08 CST 2016]; root of context hierarchy
2016-02-16 00:14:09.756  INFO 1481 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-02-16 00:14:09.763  INFO 1481 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2016-02-16 00:14:09.807  INFO 1481 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2016-02-16 00:14:09.897  INFO 1481 --- [           main] com.codecraft.RedisdemoApplication      : Started RedisdemoApplication in 2.215 seconds (JVM running for 2.589)
Message received: "Message 1, pool-1-thread-1"
Message received: "Message 2, pool-1-thread-1"
Message received: "Message 3, pool-1-thread-1"
Message received: "Message 4, pool-1-thread-1"
Message received: "Message 5, pool-1-thread-1"
Message received: "Message 6, pool-1-thread-1"
Message received: "Message 7, pool-1-thread-1"
Message received: "Message 8, pool-1-thread-1"
Message received: "Message 9, pool-1-thread-1"
Message received: "Message 10, pool-1-thread-1"

以上是redis的发布订阅功能的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:segmentfault。如有侵权,请联系admin@php.cn删除
REDIS:探索其核心功能和好处REDIS:探索其核心功能和好处Apr 30, 2025 am 12:22 AM

Redis的核心功能包括内存存储和持久化机制。1)内存存储提供极快的读写速度,适用于高性能应用。2)持久化通过RDB和AOF两种方式确保数据不丢失,选择依据应用需求。

REDIS的服务器端操作:它提供的REDIS的服务器端操作:它提供的Apr 29, 2025 am 12:21 AM

Redis'sserver-sedierations offerfunctions andTriggersForexeCutingCompleXoperationsontheserver.1)函数函数sallowCoustomoperationsinlua,javascript,javascript,orredis'sscriptinglanguage,增强效率和维护。2)

REDIS:数据库还是服务器?揭开角色的神秘面纱REDIS:数据库还是服务器?揭开角色的神秘面纱Apr 28, 2025 am 12:06 AM

redisisbothadatabaseandaserver.1)asadatabase,ituseSin-memorystorageforfastaccess,ifealforreal-timeapplications andCaching.2)Asaserver,ItsupportsPub/submessagingAndluAsessingandluAsessingandluascriptingftingftingftingftingftingftingftingfinteral-timecommunicationandserverserverserverserverserverserverserver-soperations。

REDIS:NOSQL方法的优势REDIS:NOSQL方法的优势Apr 27, 2025 am 12:09 AM

Redis是NoSQL数据库,提供高性能和灵活性。1)通过键值对存储数据,适合处理大规模数据和高并发。2)内存存储和单线程模型确保快速读写和原子性。3)使用RDB和AOF机制进行数据持久化,支持高可用性和横向扩展。

REDIS:了解其架构和目的REDIS:了解其架构和目的Apr 26, 2025 am 12:11 AM

Redis是一种内存数据结构存储系统,主要用作数据库、缓存和消息代理。它的核心特点包括单线程模型、I/O多路复用、持久化机制、复制与集群功能。 Redis在实际应用中常用于缓存、会话存储和消息队列,通过选择合适的数据结构、使用管道和事务、以及进行监控和调优,可以显着提升其性能。

REDIS与SQL数据库:关键差异REDIS与SQL数据库:关键差异Apr 25, 2025 am 12:02 AM

Redis和SQL数据库的主要区别在于:Redis是内存数据库,适用于高性能和灵活性需求;SQL数据库是关系型数据库,适用于复杂查询和数据一致性需求。具体来说,1)Redis提供高速数据访问和缓存服务,支持多种数据类型,适用于缓存和实时数据处理;2)SQL数据库通过表格结构管理数据,支持复杂查询和事务处理,适用于电商和金融系统等需要数据一致性的场景。

REDIS:它如何充当数据存储和服务REDIS:它如何充当数据存储和服务Apr 24, 2025 am 12:08 AM

REDISACTSASBOTHADATASTOREANDASERVICE.1)ASADATASTORE,ITUSESIN-MEMORYSTOOGATOFORFOFFASTESITION,支持VariousDatharptructuresLikeKey-valuepairsandsortedsetsetsetsetsetsetsets.2)asaservice,ItprovidespunctionslikeItionitionslikepunikeLikePublikePublikePlikePlikePlikeAndluikeAndluAascriptingiationsmpleplepleclexplectiations

REDIS与其他数据库:比较分析REDIS与其他数据库:比较分析Apr 23, 2025 am 12:16 AM

Redis与其他数据库相比,具有以下独特优势:1)速度极快,读写操作通常在微秒级别;2)支持丰富的数据结构和操作;3)灵活的使用场景,如缓存、计数器和发布订阅。选择Redis还是其他数据库需根据具体需求和场景,Redis在高性能、低延迟应用中表现出色。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。