Jedis的Publish/Subscribe功能的运用

转自:http://kingxss.iteye.com/blog/1420264

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

1.下载Redis

   下载地址:http://redis.googlecode.com/files/redis-2.4.8.tar.gz

 

2.安装Redis

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

Shell代码   收藏代码
  1. $ tar xzf redis-2.4.8.tar.gz  
  2. $ cd redis-2.4.8  
  3. $ make  

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

Shell代码   收藏代码
  1. $./redis-server  

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

Shell代码   收藏代码
  1. $ ./redis-server redis.conf  

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

Shell代码   收藏代码
  1. $ ./redis-cli  
  2. redis> set foo bar  
  3. OK  
  4. redis> get foo  
  5. "bar"  

这里演示了get和set命令操作简单类型value的例子。foo是key ,bar是个string类型的value。没linux的可以通过这个在线的来练习,当然在线版的很多管理相关的命令是不支持的。http://try.redis-db.com/

 

3.测试安装

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

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

Xml代码   收藏代码
  1. <dependency>  
  2.     <groupId>redis.clients</groupId>  
  3.     <artifactId>jedis</artifactId>  
  4.     <version>2.0.0</version>  
  5.     <type>jar</type>  
  6.     <scope>compile</scope>  
  7. </dependency><span style="background-color: #ffffff;">    </span>  

下面是个hello,world程序

Java代码   收藏代码
  1. package demo;  
  2. import org.jredis.*;  
  3. import org.jredis.ri.alphazero.JRedisClient;  
  4. public class App {  
  5. public static void main(String[] args) {  
  6. try {  
  7.              JRedis  jr = new JRedisClient("*.*.*.*",6379); //redis服务地址和端口号  
  8.              String key = "mKey";  
  9.              jr.set(key, "hello,redis!");  
  10.              String v = new String(jr.get(key));  
  11.              String k2 = "count";  
  12.              jr.incr(k2);  
  13.              jr.incr(k2);  
  14.              System.out.println(v);  
  15.              System.out.println(new String(jr.get(k2)));  
  16.         } catch (Exception e) {  
  17.   
  18.         }  
  19.     }  
  20. }   

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

 

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

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

 

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

Xml代码   收藏代码
  1. <dependency>  
  2.     <groupId>org.springframework</groupId>  
  3.     <artifactId>spring-context</artifactId>  
  4.     <version>3.1.1.RELEASE</version>  
  5.     <type>jar</type>  
  6.     <scope>compile</scope>  
  7. </dependency>  
  8. <dependency>  
  9.     <groupId>org.springframework</groupId>  
  10.     <artifactId>spring-context-support</artifactId>  
  11.     <version>3.1.1.RELEASE</version>  
  12.     <type>jar</type>  
  13.     <scope>compile</scope>  
  14. </dependency>  
  15. <dependency>  
  16.     <groupId>org.springframework</groupId>  
  17.     <artifactId>spring-beans</artifactId>  
  18.     <version>3.1.1.RELEASE</version>  
  19.     <type>jar</type>  
  20.     <scope>compile</scope>  
  21. </dependency>  
  22. <dependency>  
  23.     <groupId>org.springframework</groupId>  
  24.     <artifactId>spring-core</artifactId>  
  25.     <version>3.1.1.RELEASE</version>  
  26.     <type>jar</type>  
  27.     <scope>compile</scope>  
  28. </dependency>  

 

 

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

Xml代码   收藏代码
  1. <!-- pool配置 -->  
  2. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  3.     <property name="maxActive" value="20" />  
  4.     <property name="maxIdle" value="10" />  
  5.     <property name="maxWait" value="1000" />  
  6.     <property name="testOnBorrow" value="true" />  
  7. </bean>  
  8. <!-- jedis pool配置 -->  
  9. <bean id="jedisPool" class="redis.clients.jedis.JedisPool">  
  10.     <constructor-arg index="0" ref="jedisPoolConfig" />  
  11.     <constructor-arg index="1" value="10.8.9.237" />  
  12.     <constructor-arg index="2" value="6379" />  
  13. </bean>  
  14. <!-- 包装类 -->  
  15. <bean id="redisUtil" class="demo.RedisUtil">  
  16.     <property name="jedisPool" ref="jedisPool" />  
  17. </bean>  

 

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

 

Java代码   收藏代码
  1. package demo;  
  2.   
  3. import redis.clients.jedis.Jedis;  
  4. import redis.clients.jedis.JedisPool;  
  5.   
  6.   
  7. /**   
  8.  * 连接和使用redis资源的工具类     
  9.  * @author watson    
  10.  * @version 0.5    
  11.  */   
  12. public class RedisUtil {  
  13.       
  14.     /**        
  15.      * 数据源       
  16.      */       
  17.     private JedisPool jedisPool;  
  18.       
  19.     /**       
  20.      * 获取数据库连接        
  21.      * @return conn        
  22.      */       
  23.     public Jedis getConnection() {  
  24.         Jedis jedis=null;            
  25.         try {                
  26.             jedis=jedisPool.getResource();            
  27.         } catch (Exception e) {                
  28.             e.printStackTrace();            
  29.         }            
  30.         return jedis;        
  31.     }     
  32.       
  33.     /**        
  34.      * 关闭数据库连接        
  35.      * @param conn        
  36.      */       
  37.     public void closeConnection(Jedis jedis) {            
  38.         if (null != jedis) {                
  39.             try {                    
  40.                 jedisPool.returnResource(jedis);                
  41.             } catch (Exception e) {  
  42.                     e.printStackTrace();                
  43.             }            
  44.         }        
  45.     }    
  46.       
  47.     /**        
  48.      * 设置连接池        
  49.      * @param 数据源       
  50.      */       
  51.     public void setJedisPool(JedisPool JedisPool) {  
  52.         this.jedisPool = JedisPool;        
  53.     }         
  54.       
  55.     /**        
  56.      * 获取连接池        
  57.      * @return 数据源        
  58.      */       
  59.     public JedisPool getJedisPool() {  
  60.         return jedisPool;        
  61.     }       
  62. }   

 

 

4.编写Lister

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

Java代码   收藏代码
  1. package demo;  
  2.   
  3. import redis.clients.jedis.JedisPubSub;  
  4.   
  5. public class MyListener extends JedisPubSub {  
  6.     // 取得订阅的消息后的处理  
  7.     public void onMessage(String channel, String message) {  
  8.         System.out.println(channel + "=" + message);  
  9.     }  
  10.   
  11.     // 初始化订阅时候的处理  
  12.     public void onSubscribe(String channel, int subscribedChannels) {  
  13.         // System.out.println(channel + "=" + subscribedChannels);  
  14.     }  
  15.   
  16.     // 取消订阅时候的处理  
  17.     public void onUnsubscribe(String channel, int subscribedChannels) {  
  18.         // System.out.println(channel + "=" + subscribedChannels);  
  19.     }  
  20.   
  21.     // 初始化按表达式的方式订阅时候的处理  
  22.     public void onPSubscribe(String pattern, int subscribedChannels) {  
  23.         // System.out.println(pattern + "=" + subscribedChannels);  
  24.     }  
  25.   
  26.     // 取消按表达式的方式订阅时候的处理  
  27.     public void onPUnsubscribe(String pattern, int subscribedChannels) {  
  28.         // System.out.println(pattern + "=" + subscribedChannels);  
  29.     }  
  30.   
  31.     // 取得按表达式的方式订阅的消息后的处理  
  32.     public void onPMessage(String pattern, String channel, String message) {  
  33.         System.out.println(pattern + "=" + channel + "=" + message);  
  34.     }  
  35. }  

 

  5.实现订阅动能

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

Java代码   收藏代码
  1. ApplicationContext ac = <span style="background-color: #ffffff;">new ClassPathXmlApplicationContext("beans-config.xml");</span>  
  2. RedisUtil ru = (RedisUtil) ac.getBean("redisUtil");   
  3. final Jedis jedis = ru.getConnection();  
  4. final MyListener listener = new MyListener();  
  5. //可以订阅多个频道  
  6. //订阅得到信息在lister的onMessage(...)方法中进行处理  
  7. //jedis.subscribe(listener, "foo", "watson");  
  8.   
  9. //也用数组的方式设置多个频道  
  10. //jedis.subscribe(listener, new String[]{"hello_foo","hello_test"});  
  11.   
  12. //这里启动了订阅监听,线程将在这里被阻塞  
  13. //订阅得到信息在lister的onPMessage(...)方法中进行处理  
  14. jedis.psubscribe(listener, new String[]{"hello_*"});//使用模式匹配的方式设置频道  

 

6.实现发布端代码

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

 

Java代码   收藏代码
  1. ApplicationContext ac = new ClassPathXmlApplicationContext("beans-config.xml");  
  2. RedisUtil ru = (RedisUtil) ac.getBean("redisUtil");   
  3. Jedis jedis = ru.getConnection();  
  4. jedis.publish("hello_foo""bar123");  
  5. jedis.publish("hello_test""hello watson");  

 

 

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

 

输出代码   收藏代码
  1. hello_*=hello_foo=bar123  
  2. hello_*=hello_test=hello watson  

 

 

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

 

redis的安装参考:

  1. 官方:http://redis.io/topics/quickstart
  2. 中文:http://www.cnblogs.com/redcreen/archive/2011/02/15/1955523.html

参考:

  1. Jedis的高级使用:https://github.com/xetorthio/jedis/wiki/AdvancedUsage
  2. netty里集成spring注入jedis:http://yifangyou.blog.51cto.com/900206/628163
  3. Redis的Publish/Subscribe命令的使用:http://redis.io/topics/pubsub
  4. Redis的使用:http://redis.io/

猜你喜欢

转载自xinklabi.iteye.com/blog/2195245