Redis Java客户端Jredis

来源:互联网 发布:淘宝生死狙击卖号平台 编辑:程序博客网 时间:2024/05/29 23:47
JRedis 是一个高性能的 Java 客户端,用来连接到Redis分布式哈希键-值数据库。提供同步和异步的连接。

项目地址:https://github.com/alphazero/jredis


由于jreds的jar包不在公网的maven仓库中,所以需要下载源码使用如下命令,将jar添加到本地maven仓库中。

cd jredis-master\core

mvn -Dmaven.test.skip=true install

在工程pom.xml中添加依赖:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <dependency>  
  2.             <groupId>org.jredis</groupId>  
  3.             <artifactId>jredis-core-all</artifactId>  
  4.             <version>a.0-SNAPSHOT</version>  
  5.         </dependency>  
1.简单实例

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package cn.slimsmart.redis.demo.jredis;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.jredis.JRedis;  
  6. import org.jredis.RedisException;  
  7. import org.jredis.ri.alphazero.JRedisClient;  
  8. import org.jredis.ri.alphazero.support.DefaultCodec;  
  9.   
  10. public class JredisTest {  
  11.   
  12.     public static void main(String[] args) throws Exception {  
  13.         JRedis jredis = new JRedisClient("192.168.36.189"6379);  
  14.         //jredis.auth(password);  
  15.         try {  
  16.             jredis.ping();  
  17.             //是否通  
  18.             //清空数据库  
  19.             jredis.flushdb();  
  20.         } catch (RedisException e) {  
  21.             e.printStackTrace();  
  22.         }  
  23.         jredis.set("key""abc");  
  24.         if(jredis.exists("key")){    
  25.            System.out.println(new String(jredis.get("key")));  
  26.         }    
  27.           
  28.         //保存单个对象  
  29.         User user = new User();  
  30.         user.setBirthDate(new Date());  
  31.         user.setName("jack");  
  32.         jredis.set("user", user);  
  33.         System.out.println(DefaultCodec.decode(jredis.get("user")));  
  34.         //集合  
  35.         jredis.sadd("userList", user);  
  36.         user = new User();  
  37.         user.setBirthDate(new Date());  
  38.         user.setName("lucy");  
  39.         jredis.sadd("userList", user);  
  40.         System.out.println(DefaultCodec.decode(jredis.smembers("userList")));  
  41.           
  42.         //关闭  
  43.         jredis.quit();  
  44.     }  
  45.   
  46. }  
除此之外,jredis连接redis服务器端还可以使用如下方式:

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. ConnectionSpec connectionSpec = DefaultConnectionSpec.newSpec("192.168.36.189"63790,null);  
  2.          connectionSpec.setReconnectCnt(100);    
  3.          //connectionSpec.setConnectionFlag(Connection.Flag.RELIABLE, Boolean.TRUE);  
  4.          //connectionSpec.setHeartbeat(2);    
  5.          connectionSpec.setMaxConnectWait(3000);  
  6.          //JRedis jredis = new JRedisClient(connectionSpec);  
  7.          JRedis jredis = new JRedisPipelineService(connectionSpec);   
  8.          jredis.ping();  
  9.          jredis.set("key""abc");  
  10.          System.out.println(new String(jredis.get("key")));  
  11.          jredis.quit();  

2.连接池

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package cn.slimsmart.redis.demo.jredis;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;  
  6. import org.jredis.JRedis;  
  7. import org.jredis.connector.ConnectionSpec;  
  8. import org.jredis.ri.alphazero.connection.DefaultConnectionSpec;  
  9. import org.jredis.ri.alphazero.support.DefaultCodec;  
  10. import org.springframework.data.redis.connection.jredis.JredisPool;  
  11.   
  12. public class JredisPoolTest {  
  13.   
  14.     public static void main(String[] args) throws Exception {  
  15.         //链接配置  
  16.          ConnectionSpec connectionSpec = DefaultConnectionSpec.newSpec("192.168.36.189"63790,null);  
  17.          connectionSpec.setReconnectCnt(100);    
  18.          //connectionSpec.setConnectionFlag(Connection.Flag.RELIABLE, Boolean.TRUE);  
  19.          //connectionSpec.setHeartbeat(5);    
  20.          connectionSpec.setMaxConnectWait(3000);  
  21.         //连接池配置  
  22.         GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();  
  23.         poolConfig.setMaxTotal(10);  
  24.         poolConfig.setMinIdle(2);  
  25.         poolConfig.setMaxIdle(10);  
  26.         poolConfig.setMaxWaitMillis(3000);  
  27.         poolConfig.setTestOnBorrow(true);  
  28.         poolConfig.setTestOnReturn(true);  
  29.         poolConfig.setTestWhileIdle(true);  
  30.         poolConfig.setTimeBetweenEvictionRunsMillis(3000);  
  31.           
  32.         JredisPool jredisPool = new JredisPool(connectionSpec,poolConfig);  
  33.         //获取链接  
  34.         JRedis jredis = jredisPool.getResource();  
  35.         jredis.set("key""abc");  
  36.         if(jredis.exists("key")){    
  37.            System.out.println(new String(jredis.get("key")));  
  38.         }    
  39.         //保存单个对象  
  40.         User user = new User();  
  41.         user.setBirthDate(new Date());  
  42.         user.setName("jack");  
  43.         jredis.set("user", user);  
  44.         System.out.println(DefaultCodec.decode(jredis.get("user")));  
  45.         //回收  
  46.         jredisPool.returnResource(jredis);  
  47.     }  
  48. }  

3.Fail tolerance

要保证一个client连接到slave服务上读取数据,如果slave down 了之后,可以在不影响应用的情况下,自动切换到另外一个可用的slave。因为jredis不支持设置多个slave服务器,所以写了一个小工具类,目的是为了探测如果的当前正在使用的slave没有heartbeat之后,立马可以切换到一个可用的slave;这样可以保证one of slave down掉之后,不用missing-load也可及时切换到另外一个slave上读数据。

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package cn.slimsmart.redis.demo.jredis;  
  2.   
  3. import java.util.HashMap;  
  4.   
  5. import org.jredis.JRedis;  
  6. import org.jredis.connector.ConnectionSpec;  
  7. import org.jredis.ri.alphazero.JRedisClient;  
  8. import org.jredis.ri.alphazero.connection.DefaultConnectionSpec;  
  9. import org.jredis.ri.alphazero.support.DefaultCodec;  
  10.   
  11. public class RedisFailTolerance {  
  12.     private static JRedis jredis = null;  
  13.   
  14.     private static ConnectionSpec defaultConnectionSpec = null;  
  15.   
  16.     private static int current = 1;  
  17.   
  18.     private static HashMap<String, ConnectionSpec> serverPools = new HashMap<String, ConnectionSpec>();  
  19.     static {  
  20.         ConnectionSpec connectionSpec1 = DefaultConnectionSpec.newSpec("192.168.36.189"63790null);  
  21.         ConnectionSpec connectionSpec2 = DefaultConnectionSpec.newSpec("192.168.36.54"63790null);  
  22.         serverPools.put("1", connectionSpec1);  
  23.         serverPools.put("2", connectionSpec2);  
  24.     }  
  25.   
  26.     private String next() {  
  27.         if (current > serverPools.size()) {  
  28.             current = 1;  
  29.         }  
  30.         int nextIndex = current;  
  31.         current++;  
  32.         return nextIndex + "";  
  33.     }  
  34.   
  35.     private ConnectionSpec getConnectionSpec() {  
  36.         if (defaultConnectionSpec != null) {  
  37.             return defaultConnectionSpec;  
  38.         }  
  39.   
  40.         jredis = null;  
  41.         /** 
  42.          * we are working multiple servers try different servers,util we fetch 
  43.          * the first available server pool 
  44.          */  
  45.         HashMap<String, ConnectionSpec> tryServers = new HashMap<String, ConnectionSpec>(serverPools);  
  46.         if (serverPools.size() == 1) {  
  47.             return (ConnectionSpec) serverPools.get("1");  
  48.         }  
  49.   
  50.         while (!tryServers.isEmpty()) {  
  51.             ConnectionSpec connectionSpec = tryServers.get(this.next());  
  52.   
  53.             if (isConnect(connectionSpec)) {  
  54.                 return connectionSpec;  
  55.             }  
  56.   
  57.             tryServers.remove(connectionSpec);  
  58.             if (tryServers.isEmpty()) {  
  59.                 break;  
  60.             }  
  61.         }  
  62.   
  63.         return null;  
  64.     }  
  65.   
  66.     /** 
  67.      * try whether the server is available 
  68.      *  
  69.      * @param connectionSpec 
  70.      * @return true or false 
  71.      */  
  72.     private boolean isConnect(ConnectionSpec connectionSpec) {  
  73.         if (connectionSpec == null) {  
  74.             return false;  
  75.         }  
  76.   
  77.         JRedis jredis = new JRedisClient(connectionSpec.getAddress().getHostAddress(), connectionSpec.getPort());  
  78.         try {  
  79.             jredis.ping();  
  80.             jredis.quit();  
  81.         } catch (Exception e) {  
  82.             return false;  
  83.         }  
  84.         return true;  
  85.     }  
  86.   
  87.     public void initialize() {  
  88.         defaultConnectionSpec = this.getConnectionSpec();  
  89.         if (jredis == null) {  
  90.             synchronized (this) {  
  91.                 jredis = new JRedisClient(defaultConnectionSpec);  
  92.             }  
  93.         }  
  94.     }  
  95.   
  96.     public String getS(String key) {  
  97.         this.initialize();  
  98.         String value = null;  
  99.         try {  
  100.             value = DefaultCodec.toStr(jredis.get(key));  
  101.         } catch (Exception e) {  
  102.             e.printStackTrace();  
  103.             defaultConnectionSpec = null;  
  104.             this.initialize();  
  105.         }  
  106.   
  107.         return value;  
  108.     }  
  109.   
  110.     public static void main(String args[]) {  
  111.         RedisFailTolerance redis = new RedisFailTolerance();  
  112.         System.out.println(redis.getS("key"));  
  113.         try {  
  114.             Thread.sleep(1000);  
  115.         } catch (InterruptedException e) {  
  116.             e.printStackTrace();  
  117.         }  
  118.         System.out.println(redis.getS("key"));  
  119.         try {  
  120.             Thread.sleep(3000);  
  121.         } catch (InterruptedException e) {  
  122.             e.printStackTrace();  
  123.         }  
  124.         System.out.println(redis.getS("key"));  
  125.     }  
  126. }  
参考:http://dmouse.iteye.com/blog/813026

4.与spring集成,参考:http://blog.csdn.net/zhu_tianwei/article/details/44900219

0 0
原创粉丝点击