`
liyonghui160com
  • 浏览: 771703 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

redis-2.8.13 jedis实现订阅发布-publish/subscribe

阅读更多

 

一、Redis服务器端的安装和客户端Jedis的安装

1.下载Redis

   下载地址:http://download.redis.io/releases/redis-2.8.13.tar.gz

2.安装Redis

在linux下运行如下命令进行安装。

$ wget http://download.redis.io/releases/redis-2.8.13.tar.gz
$ tar xzf redis-2.8.13.tar.gz
$ cd redis-2.8.13
$ make

make完后 redis-2.8.13目录下会出现编译后的redis服务程序redis-server,还有用于测试的客户端程序redis-cli。下面启动redis服务.

    $ src/redis-server

注意这种方式启动redis 使用的是默认配置。也可以通过启动参数告诉redis使用指定配置文件使用下面命令启动.

    $ src/redis-server redis.conf 

 redis.conf是一个默认的配置文件。我们可以根据需要使用自己的配置文件。启动redis服务进程后,就可以使用测试客户端程序redis-cli和redis服务交互了.比如

    $ src/redis-cli 
    redis> set foo bar 
    OK 
    redis> get foo 
    "bar" 

 

集群配置


  用一致性哈希,做多个主从,可以做主从集群。
  主从配置
  配置Master-Slave,只需要在Slave上配置Master节点IP Port:
  # slaveof <masterip> <masterport> 
  修改上面最后一行
  slaveof 10.3.7.212 6379 

 

启动slave
$ src/redis-server ./redis.conf

 

测试
Master写,Slave读:



3.客户端

Jedis是官方推荐的连接redis的客户端,客户端jar包地址:http://cloud.github.com/downloads/xetorthio/jedis/jedis-2.0.0.jar。

在eclipse中新建一个java项目,然后添加jredis包引用。或者可以创建Maven项目,导入jedis代码如下

    <dependency> 
        <groupId>redis.clients</groupId> 
        <artifactId>jedis</artifactId> 
        <version>2.0.0</version> 
        <type>jar</type> 
        <scope>compile</scope> 
    </dependency><span style="background-color: #ffffff;">    </span> 

下面是个hello,world程序

    package demo; 
    import org.jredis.*; 
    import org.jredis.ri.alphazero.JRedisClient; 
    public class App { 
    public static void main(String[] args) { 
    try { 
                 JRedis  jr = new JRedisClient("*.*.*.*",6379); //redis服务地址和端口号 
                 String key = "mKey"; 
                 jr.set(key, "hello,redis!"); 
                 String v = new String(jr.get(key)); 
                 String k2 = "count"; 
                 jr.incr(k2); 
                 jr.incr(k2); 
                 System.out.println(v); 
                 System.out.println(new String(jr.get(k2))); 
            } catch (Exception e) { 
     
            } 
        } 
    }  

运行测试客户端,如果能够看到正确的输出,那么redis环境已经搭建好了。

二、Jedis的Publish/Subscribe功能的使用

由于redis内置了发布/订阅功能,可以作为消息机制使用。所以这里主要使用Jedis的Publish/Subscribe功能。

1.添加Spring核心包,主要使用其最核心的IoC功能。如果使用Maven,配置如下:

    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-context</artifactId> 
        <version>3.1.1.RELEASE</version> 
        <type>jar</type> 
        <scope>compile</scope> 
    </dependency> 
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-context-support</artifactId> 
        <version>3.1.1.RELEASE</version> 
        <type>jar</type> 
        <scope>compile</scope> 
    </dependency> 
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-beans</artifactId> 
        <version>3.1.1.RELEASE</version> 
        <type>jar</type> 
        <scope>compile</scope> 
    </dependency> 
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-core</artifactId> 
        <version>3.1.1.RELEASE</version> 
        <type>jar</type> 
        <scope>compile</scope> 
    </dependency> 


2.使用Spring来配置Jedis连接池和RedisUtil的注入,写在bean-config.xml中。

    <!-- pool配置 --> 
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 
        <property name="maxActive" value="20" /> 
        <property name="maxIdle" value="10" /> 
        <property name="maxWait" value="1000" /> 
        <property name="testOnBorrow" value="true" /> 
    </bean> 
    <!-- jedis pool配置 --> 
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool"> 
        <constructor-arg index="0" ref="jedisPoolConfig" /> 
        <constructor-arg index="1" value="10.8.9.237" /> 
        <constructor-arg index="2" value="6379" /> 
    </bean> 
    <!-- 包装类 --> 
    <bean id="redisUtil" class="demo.RedisUtil"> 
        <property name="jedisPool" ref="jedisPool" /> 
    </bean> 


3.编写RedisUtil,这里只是简单的包装,不做解释。

    package demo; 
     
    import redis.clients.jedis.Jedis; 
    import redis.clients.jedis.JedisPool; 
     
     
    /**  
     * 连接和使用redis资源的工具类    
     * @author watson   
     * @version 0.5   
     */  
    public class RedisUtil { 
         
        /**       
         * 数据源      
         */      
        private JedisPool jedisPool; 
         
        /**      
         * 获取数据库连接       
         * @return conn       
         */      
        public Jedis getConnection() { 
            Jedis jedis=null;           
            try {               
                jedis=jedisPool.getResource();           
            } catch (Exception e) {               
                e.printStackTrace();           
            }           
            return jedis;       
        }    
         
        /**       
         * 关闭数据库连接       
         * @param conn       
         */      
        public void closeConnection(Jedis jedis) {           
            if (null != jedis) {               
                try {                   
                    jedisPool.returnResource(jedis);               
                } catch (Exception e) { 
                        e.printStackTrace();               
                }           
            }       
        }   
         
        /**       
         * 设置连接池       
         * @param 数据源      
         */      
        public void setJedisPool(JedisPool JedisPool) { 
            this.jedisPool = JedisPool;       
        }        
         
        /**       
         * 获取连接池       
         * @return 数据源       
         */      
        public JedisPool getJedisPool() { 
            return jedisPool;       
        }      
    }  

4.编写Lister

要使用Jedis的Publish/Subscribe功能,必须编写对JedisPubSub的自己的实现,其中的函数的功能如下:

    package demo; 
     
    import redis.clients.jedis.JedisPubSub; 
     
    public class MyListener extends JedisPubSub { 
        // 取得订阅的消息后的处理 
        public void onMessage(String channel, String message) { 
            System.out.println(channel + "=" + message); 
        } 
     
        // 初始化订阅时候的处理 
        public void onSubscribe(String channel, int subscribedChannels) { 
            // System.out.println(channel + "=" + subscribedChannels); 
        } 
     
        // 取消订阅时候的处理 
        public void onUnsubscribe(String channel, int subscribedChannels) { 
            // System.out.println(channel + "=" + subscribedChannels); 
        } 
     
        // 初始化按表达式的方式订阅时候的处理 
        public void onPSubscribe(String pattern, int subscribedChannels) { 
            // System.out.println(pattern + "=" + subscribedChannels); 
        } 
     
        // 取消按表达式的方式订阅时候的处理 
        public void onPUnsubscribe(String pattern, int subscribedChannels) { 
            // System.out.println(pattern + "=" + subscribedChannels); 
        } 
     
        // 取得按表达式的方式订阅的消息后的处理 
        public void onPMessage(String pattern, String channel, String message) { 
            System.out.println(pattern + "=" + channel + "=" + message); 
        } 
    } 

  5.实现订阅动能

Jedis有两种订阅模式:subsribe(一般模式设置频道)和psubsribe(使用模式匹配来设置频道)。不管是那种模式都可以设置个数不定的频道。订阅得到信息在将会lister的onMessage(...)方法或者onPMessage(...)中进行进行处理,这里我们只是做了简单的输出。

    ApplicationContext ac =new ClassPathXmlApplicationContext("beans-config.xml");
    RedisUtil ru = (RedisUtil) ac.getBean("redisUtil");  
    final Jedis jedis = ru.getConnection(); 
    final MyListener listener = new MyListener(); 
    //可以订阅多个频道 
    //订阅得到信息在lister的onMessage(...)方法中进行处理 
    //jedis.subscribe(listener, "foo", "watson"); 
     
    //也用数组的方式设置多个频道 
    //jedis.subscribe(listener, new String[]{"hello_foo","hello_test"}); 
     
    //这里启动了订阅监听,线程将在这里被阻塞 
    //订阅得到信息在lister的onPMessage(...)方法中进行处理 
    jedis.psubscribe(listener, new String[]{"hello_*"});//使用模式匹配的方式设置频道 

6.实现发布端代码

发布消息只用调用Jedis的publish(...)方法即可。

    ApplicationContext ac = new ClassPathXmlApplicationContext("beans-config.xml"); 
    RedisUtil ru = (RedisUtil) ac.getBean("redisUtil");  
    Jedis jedis = ru.getConnection(); 
    jedis.publish("hello_foo", "bar123"); 
    jedis.publish("hello_test", "hello watson"); 

7.分别运行上面的第5步的订阅端代码和第6步的发布端的代码,订阅端就可以得到发布端发布的结果。控制台输出结果如下:

    hello_*=hello_foo=bar123 
    hello_*=hello_test=hello watson 

 
至此Jedis的Publish/Subscribe功能的使用基本展示完成,该使用方法稍作完善和修改后即可用于生产环境。

分享到:
评论
1 楼 xinglianxlxl 2017-10-12  
订阅发布对我有用

相关推荐

    redis-2.8.13安装配置主从服务器Master-Slave

    tar xzf redis-2.8.13.tar.gz cd redis-2.8.13 make sudo make install ``` 安装完成后,启动Redis服务: ``` src/redis-server ``` **2. 配置主服务器** 在`redis.conf`配置文件中,保持默认设置,启动主服务器: ...

    redis-linux-2.8.13.rar

    3. **发布/订阅(Pub/Sub)**:Redis支持发布/订阅模式,允许客户端订阅特定的频道并接收来自服务器的广播消息。这是构建实时消息系统或实现异步通信的基础。 4. **事务(Transaction)**:虽然Redis的事务不如传统SQL...

    redis-5.0.4.tar.gz下载及redis安装过程

    1: 下载redis-5.0.4.tar.gz 2: 解压源码并进入目录 tar zxvf redis-5.0.4.tar.gz cd redis-5.0.4 3: 不用configure 4: 直接make (如果是32位机器 make 32bit) 查看linux机器是32位还是64位的方法:file /bin/...

    redis+redis-desktop-manager-0.8.3.3850+笔记

    1. 下载源码包:`redis-2.8.13.tar.gz` 是Redis的源码包,解压后进行编译和安装。 2. 解压:`tar -zxvf redis-2.8.13.tar.gz` 3. 编译:`cd redis-2.8.13`,然后`make` 4. 安装:`sudo make install` 5. 启动Redis...

    Redis-x64-5.0.14.1

    - **发布/订阅**:支持消息订阅和发布功能,可用于实现简单的消息队列。 2. **Windows上的安装和配置**: - `redis.windows-service.conf`和`redis.windows.conf`是Redis的配置文件。前者用于以服务方式启动Redis...

    Redis稳定版 Redis-x64-5.0.14.1.zip

    5. **发布/订阅**: Redis的发布/订阅功能允许客户端订阅特定的频道,当有消息发布到该频道时,所有订阅者都会收到消息,常用于实现消息通知或者异步处理。 6. **Lua脚本**: Redis支持在服务端执行Lua脚本,可以进行...

    tomcat-redis-session-manager包集合下载(tomcat8)

    【标题】"tomcat-redis-session-manager包集合下载(tomcat8)"涉及的主要知识点是将Redis集成到Tomcat中管理会话(session),以提高Web应用的性能和可扩展性。 【描述】中提到的"所需的tomcat-redis-session-...

    redis-windows-7.2.4.zip

    - **发布订阅**:Redis提供了发布/订阅模式,用于实现消息传递和事件驱动。 - **Lua脚本**:用户可以通过Lua脚本来实现更复杂的数据处理逻辑。 - **限流**:Redis提供了限速功能,可以帮助控制请求速率,防止服务...

    tomcat-redis-session-manager-master-2.0.0

    1.添加 redis session 集群依赖的jar包到 tomcat/lib 目录下 tomcat-redis-session-manager-2.0.0.jar jedis-2.5.2.jar commons-pool2-2.2.jar 2.修改 conf 目录下的 context.xml 文件 ...

    session 共享 tomcat-redis-session-manager 所需要的jar (绝对可用)

    Jedis提供了丰富的API,支持连接池、事务处理、发布/订阅等功能,使得在Java应用中操作Redis变得简单。 2. "commons-pool2-2.0.jar":Apache Commons Pool是一个对象池设计模式的实现,主要用于管理和复用昂贵资源...

    tomcat-redis-session-manager的jar包-包含Tomcat7和Tomcat8

    在压缩包中的两个jar文件,`tomcat8-redis-session-manager-2.0.0.jar`和`tomcat7-redis-session-manager-2.0.0.jar`,分别对应Tomcat8和Tomcat7的实现。这两个jar包包含了实现session与Redis交互的所有必要组件,如...

    redis-4.0.2 Linux版本及手写安装文档及jedis jar

    在上述代码中,`Jedis`类提供了丰富的API供开发者进行各种Redis操作,如字符串、哈希、列表、集合和有序集合的操作,以及发布/订阅、事务等高级功能。 此外,需要注意的是,为了保证数据安全和防止未授权访问,建议...

    redis-3.2.12.tar.gz和redis-3.3.3.gem.zip

    6. 消息发布与订阅:Pub/Sub模型允许客户端订阅特定频道,接收实时消息。 Redis因其高效性能而广受欢迎,但也需要注意其内存管理策略,因为Redis所有数据都存储在内存中,所以要合理设置最大内存并配合合适的持久化...

    tomcat-redis-session-manager for tomcat8.5

    压缩文件包括tomcat-redis-session-manager-master-2.0.0.jar、jedis-2.7.3.jar、commons-pool2-2.3.jar三个jar包使用方法请参照https://github.com/jcoleman/tomcat-redis-session-manager。apache-tomcat-8.5.33....

    tomcat-redis-session-manager-1.2-tomcat-7-java-7

    总之,"tomcat-redis-session-manager-1.2-tomcat-7-java-7"这个组件为Tomcat提供了一种利用Redis存储session的解决方案,通过Apache Commons Pool和Jedis实现了连接管理和通信,从而提高了Web应用的可扩展性和健壮...

    Redis-x64-5.0.9.zip

    可以使用各种语言的Redis客户端连接,如Python的`redis-py`,Java的`Jedis`等。 13. **安全策略**: Redis可以通过设置密码认证,限制只允许特定IP连接,增加安全性。 14. **监控与性能分析**: Redis提供了`...

    Redis-x64-5.0.14.1 缓存程序

    6. **发布/订阅**:Redis提供发布/订阅模式,允许客户端订阅感兴趣的频道,当有其他客户端向该频道发布消息时,订阅者会收到通知,实现简单的消息传递。 7. **限流**:通过`incrby`和`expire`命令,可以实现简单的...

    Redis-x64-3.2.100.zip

    5. **发布/订阅**:Redis支持发布订阅模式,允许客户端订阅特定的频道,当有消息发布到这些频道时,所有订阅者都会收到通知,这使得Redis可以用作简单的消息队列。 6. **Lua脚本**:Redis内置了对Lua脚本的支持,...

    redis-6.2.13.tar.gz

    4. **发布订阅(Publish/Subscribe)**: Redis提供发布订阅模式,用于实现消息传递,允许客户端订阅特定频道并接收消息。 5. **主从复制(Slave Replication)**: Redis支持主从复制,可以创建多个从节点,实现数据...

Global site tag (gtag.js) - Google Analytics