Redis Java客户端Jredis

来源:互联网 发布:amd显卡驱动linux 编辑:程序博客网 时间:2024/06/05 14:07
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中添加依赖:

<dependency><groupId>org.jredis</groupId><artifactId>jredis-core-all</artifactId><version>a.0-SNAPSHOT</version></dependency>
1.简单实例

package cn.slimsmart.redis.demo.jredis;import java.util.Date;import org.jredis.JRedis;import org.jredis.RedisException;import org.jredis.ri.alphazero.JRedisClient;import org.jredis.ri.alphazero.support.DefaultCodec;public class JredisTest {public static void main(String[] args) throws Exception {JRedis jredis = new JRedisClient("192.168.36.189", 6379);//jredis.auth(password);try {jredis.ping();//是否通//清空数据库jredis.flushdb();} catch (RedisException e) {e.printStackTrace();}jredis.set("key", "abc");if(jredis.exists("key")){     System.out.println(new String(jredis.get("key")));}  //保存单个对象User user = new User();user.setBirthDate(new Date());user.setName("jack");jredis.set("user", user);System.out.println(DefaultCodec.decode(jredis.get("user")));//集合jredis.sadd("userList", user);user = new User();user.setBirthDate(new Date());user.setName("lucy");jredis.sadd("userList", user);System.out.println(DefaultCodec.decode(jredis.smembers("userList")));//关闭jredis.quit();}}
除此之外,jredis连接redis服务器端还可以使用如下方式:

ConnectionSpec connectionSpec = DefaultConnectionSpec.newSpec("192.168.36.189", 6379, 0,null); connectionSpec.setReconnectCnt(100);   //connectionSpec.setConnectionFlag(Connection.Flag.RELIABLE, Boolean.TRUE); //connectionSpec.setHeartbeat(2);   connectionSpec.setMaxConnectWait(3000); //JRedis jredis = new JRedisClient(connectionSpec); JRedis jredis = new JRedisPipelineService(connectionSpec);  jredis.ping(); jredis.set("key", "abc"); System.out.println(new String(jredis.get("key"))); jredis.quit();

2.连接池

package cn.slimsmart.redis.demo.jredis;import java.util.Date;import org.apache.commons.pool2.impl.GenericObjectPoolConfig;import org.jredis.JRedis;import org.jredis.connector.ConnectionSpec;import org.jredis.ri.alphazero.connection.DefaultConnectionSpec;import org.jredis.ri.alphazero.support.DefaultCodec;import org.springframework.data.redis.connection.jredis.JredisPool;public class JredisPoolTest {public static void main(String[] args) throws Exception {//链接配置 ConnectionSpec connectionSpec = DefaultConnectionSpec.newSpec("192.168.36.189", 6379, 0,null); connectionSpec.setReconnectCnt(100);   //connectionSpec.setConnectionFlag(Connection.Flag.RELIABLE, Boolean.TRUE); //connectionSpec.setHeartbeat(5);   connectionSpec.setMaxConnectWait(3000);//连接池配置GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();poolConfig.setMaxTotal(10);poolConfig.setMinIdle(2);poolConfig.setMaxIdle(10);poolConfig.setMaxWaitMillis(3000);poolConfig.setTestOnBorrow(true);poolConfig.setTestOnReturn(true);poolConfig.setTestWhileIdle(true);poolConfig.setTimeBetweenEvictionRunsMillis(3000);JredisPool jredisPool = new JredisPool(connectionSpec,poolConfig);//获取链接JRedis jredis = jredisPool.getResource();jredis.set("key", "abc");if(jredis.exists("key")){     System.out.println(new String(jredis.get("key")));}  //保存单个对象User user = new User();user.setBirthDate(new Date());user.setName("jack");jredis.set("user", user);System.out.println(DefaultCodec.decode(jredis.get("user")));//回收jredisPool.returnResource(jredis);}}

3.Fail tolerance

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

package cn.slimsmart.redis.demo.jredis;import java.util.HashMap;import org.jredis.JRedis;import org.jredis.connector.ConnectionSpec;import org.jredis.ri.alphazero.JRedisClient;import org.jredis.ri.alphazero.connection.DefaultConnectionSpec;import org.jredis.ri.alphazero.support.DefaultCodec;public class RedisFailTolerance {private static JRedis jredis = null;private static ConnectionSpec defaultConnectionSpec = null;private static int current = 1;private static HashMap<String, ConnectionSpec> serverPools = new HashMap<String, ConnectionSpec>();static {ConnectionSpec connectionSpec1 = DefaultConnectionSpec.newSpec("192.168.36.189", 6379, 0, null);ConnectionSpec connectionSpec2 = DefaultConnectionSpec.newSpec("192.168.36.54", 6379, 0, null);serverPools.put("1", connectionSpec1);serverPools.put("2", connectionSpec2);}private String next() {if (current > serverPools.size()) {current = 1;}int nextIndex = current;current++;return nextIndex + "";}private ConnectionSpec getConnectionSpec() {if (defaultConnectionSpec != null) {return defaultConnectionSpec;}jredis = null;/** * we are working multiple servers try different servers,util we fetch * the first available server pool */HashMap<String, ConnectionSpec> tryServers = new HashMap<String, ConnectionSpec>(serverPools);if (serverPools.size() == 1) {return (ConnectionSpec) serverPools.get("1");}while (!tryServers.isEmpty()) {ConnectionSpec connectionSpec = tryServers.get(this.next());if (isConnect(connectionSpec)) {return connectionSpec;}tryServers.remove(connectionSpec);if (tryServers.isEmpty()) {break;}}return null;}/** * try whether the server is available *  * @param connectionSpec * @return true or false */private boolean isConnect(ConnectionSpec connectionSpec) {if (connectionSpec == null) {return false;}JRedis jredis = new JRedisClient(connectionSpec.getAddress().getHostAddress(), connectionSpec.getPort());try {jredis.ping();jredis.quit();} catch (Exception e) {return false;}return true;}public void initialize() {defaultConnectionSpec = this.getConnectionSpec();if (jredis == null) {synchronized (this) {jredis = new JRedisClient(defaultConnectionSpec);}}}public String getS(String key) {this.initialize();String value = null;try {value = DefaultCodec.toStr(jredis.get(key));} catch (Exception e) {e.printStackTrace();defaultConnectionSpec = null;this.initialize();}return value;}public static void main(String args[]) {RedisFailTolerance redis = new RedisFailTolerance();System.out.println(redis.getS("key"));try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(redis.getS("key"));try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(redis.getS("key"));}}
参考:http://dmouse.iteye.com/blog/813026

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

0 0