一、Redis服務器端的安裝和客戶端Jedis的安裝
1.下載Redis
下載地址:http://redis.googlecode.com/files/redis-2.4.8.tar.gz
2.安裝Redis
在linux下運行如下命令進行安裝。
Shell代碼

- $ 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服務.
Shell代碼

- $./redis-server
注意這種方式啟動redis 使用的是默認配置。也可以通過啟動參數告訴redis使用指定配置文件使用下面命令啟動.
Shell代碼

- $ ./redis-server redis.conf
redis.conf是一個默認的配置文件。我們可以根據需要使用自己的配置文件。啟動redis服務進程后,就可以使用測試客戶端程序redis-cli和redis服務交互了.比如
Shell代碼

- $ ./redis-cli
- redis> set foo bar
- OK
- redis> 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包引用?;蛘呖梢詣摻∕aven項目,導入jedis代碼如下
Xml代碼

- <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程序
Java代碼

- 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,配置如下:
Xml代碼

- <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中。
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,這里只是簡單的包裝,不做解釋。
Java代碼

- 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的自己的實現,其中的函數的功能如下:
Java代碼

- 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(...)中進行進行處理,這里我們只是做了簡單的輸出。
Java代碼

- 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(...)方法即可。
Java代碼

- 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功能的使用基本展示完成,該使用方法稍作完善和修改后即可用于生產環境。
redis的安裝參考:
- 官方:http://redis.io/topics/quickstart
- 中文:http://www.cnblogs.com/redcreen/archive/2011/02/15/1955523.html
參考:
- Jedis的高級使用:https://github.com/xetorthio/jedis/wiki/AdvancedUsage
- netty里集成spring注入jedis:http://yifangyou.blog.51cto.com/900206/628163
- Redis的Publish/Subscribe命令的使用:http://redis.io/topics/pubsub
- Redis的使用:http://redis.io/