Jedis的Publish/Subscribe功能的运用

来源:互联网 发布:中国房地产数据研究院 编辑:程序博客网 时间:2024/04/29 16:22

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

1.下载Redis

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

 

2.安装Redis

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

$ tar xzf redis-2.4.8.tar.gz$ cd redis-2.4.8$ make

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


 $./redis-server

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

 $ ./redis-server redis.conf

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


$ ./redis-cliredis> set foo barOKredis> get foo"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代码如下

<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 = <span style="background-color: #ffffff;">new ClassPathXmlApplicationContext("beans-config.xml");</span>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步的发布端的代码,订阅端就可以得到发布端发布的结果。控制台输出结果如下:

 

输出代码  收藏代码
  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/
来源:http://kingxss.iteye.com/blog/1420264