redis發佈訂閱消息

一、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/

關注公衆號,我們一起學java
關注公衆號,我們一起學java

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功能的使用基本展示完成,該使用方法稍作完善和修改後即可用於生產環境。

關注公衆號,我們一起學java
關注公衆號,我們一起學java

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/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章