设为首页 收藏本站
查看: 1090|回复: 0

[经验分享] redis-2.8.13 jedis实现订阅发布-publish/subscribe

[复制链接]

尚未签到

发表于 2016-12-20 08:48:58 | 显示全部楼层 |阅读模式
  一、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、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-316716-1-1.html 上篇帖子: Redis被bgsave和bgrewriteaof阻塞的解决方法 下篇帖子: 【Redis一】Redis2.4.5搭建主从复制环境
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表