Jedis的github链接https://github.com/xetorthio/jedis,请下载Master分支。
目前Jedis最新稳定版本是2.7.2,但并未合并诸如BinaryJedisCluster(提供持久化Java对象操作)等类,而最新的2.7.3主要是fix spring-data-redis在整合2.7.2的抛异常问题,Jedis-Cluster方面还在观察中,所以想要获得对Cluster操作更多更齐全的api就要稍微冒点风险下载Master分支,即Jedis-3.0-snapshot。
package com.csair.dean; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashSet; import java.util.Set; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; public class PlayJedis { public static void main(String[] args) { Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>(); //Jedis Cluster will attempt to discover cluster nodes automatically jedisClusterNodes.add(new HostAndPort("10.92.21.17", 6379)); jedisClusterNodes.add(new HostAndPort("10.92.21.17", 7379)); jedisClusterNodes.add(new HostAndPort("10.92.21.17", 8379)); jedisClusterNodes.add(new HostAndPort("10.92.21.18", 6380)); jedisClusterNodes.add(new HostAndPort("10.92.21.18", 7380)); jedisClusterNodes.add(new HostAndPort("10.92.21.18", 8380)); JedisCluster jc = new JedisCluster(jedisClusterNodes); jc.set("foo", "bar");//不设置超时 jc.setex("foo",1800, "bar");//设置1800s超时 Person p = new Person(); p.setName("DeanPhipray"); p.setGender("M"); p.setAge(30); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(p); oos.flush(); jc.set("fooMap".getBytes(), baos.toByteArray()); jc.setex("fooMap".getBytes(), 1800, baos.toByteArray()); String value = jc.get("foo"); System.out.println("foo=========="+ value); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(jc.get("fooMap".getBytes()))); Person pr = (Person) in.readObject(); System.out.println("再次为人"+ pr.getName()+"+++"+pr.getGender()+"+++"+pr.getAge()); } catch (Exception e) { //do something e.printStackTrace(); } } }
运行结果:
foo==========bar 再次为人DeanPhipray+++M+++30
---------------------------------------------------------------------------------------------------------------------------------
跟spring整合
spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> <!-- jedis configuration starts --> <bean id="config" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig"> <property name="maxTotal" value="200"></property> <property name="maxIdle" value="50"></property> <property name="minIdle" value="10"></property> <property name="maxWaitMillis" value="15000"></property> <property name="lifo" value="true"></property> <property name="blockWhenExhausted" value="true"></property> <property name="testOnBorrow" value="false"></property> <property name="testOnReturn" value="false"></property> <property name="testWhileIdle" value="true"></property> <property name="timeBetweenEvictionRunsMillis" value="30000"></property> </bean> <bean id="jedisCluster" class="com.csair.csmbp.utiltool.redis.JedisClusterFactory"> <property name="addressConfig"> <value>classpath:redis-servers.properties</value> </property> <property name="addressKeyPrefix" value="address" /> <property name="timeout" value="300000" /> <property name="maxRedirections" value="6" /> <property name="config" ref="config" /> </bean> <bean id="jedisClusterHelper" class="com.csair.csmbp.utiltool.redis.JedisClusterHelper"> <constructor-arg index="0" name="jedisCluster" type="redis.clients.jedis.JedisCluster" ref="jedisCluster" /> <property name="timeOut" value="1800" /> </bean> <!-- jedis configuration ends --> </beans>
pom.xml 片段
。。。。。。。。 <mvn.redis.server1>10.92.21.17:6379</mvn.redis.server1> <mvn.redis.server2>10.92.21.17:7379</mvn.redis.server2> <mvn.redis.server3>10.92.21.17:8379</mvn.redis.server3> <mvn.redis.server4>10.92.21.18:6380</mvn.redis.server4> <mvn.redis.server5>10.92.21.18:7380</mvn.redis.server5> <mvn.redis.server6>10.92.21.18:8380</mvn.redis.server6> 。。。。。。。。。。。
redis-server.properties
address1=${mvn.redis.server1} address2=${mvn.redis.server2} address3=${mvn.redis.server3} address4=${mvn.redis.server4} address5=${mvn.redis.server5} address6=${mvn.redis.server6}
JedisClusterFactory
package com.csair.csmbp.utiltool.redis; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.io.Resource; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean { private final Logger logger = LoggerFactory.getLogger(getClass()); private Resource addressConfig; private String addressKeyPrefix ; private JedisCluster jedisCluster; private Integer timeout; private Integer maxRedirections; private GenericObjectPoolConfig config; private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$"); @Override public void afterPropertiesSet() throws Exception { // TODO Auto-generated method stub Set<HostAndPort> haps = this.parseHostAndPort(); jedisCluster = new JedisCluster(haps, timeout, maxRedirections,config); } @Override public JedisCluster getObject() throws Exception { // TODO Auto-generated method stub return jedisCluster; } @Override public Class<? extends JedisCluster> getObjectType() { // TODO Auto-generated method stub return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class); } @Override public boolean isSingleton() { // TODO Auto-generated method stub return false; } public void setAddressConfig(Resource addressConfig) { this.addressConfig = addressConfig; } public void setTimeout(int timeout) { this.timeout = timeout; } public void setMaxRedirections(int maxRedirections) { this.maxRedirections = maxRedirections; } public void setAddressKeyPrefix(String addressKeyPrefix) { this.addressKeyPrefix = addressKeyPrefix; } public void setConfig(GenericObjectPoolConfig config) { this.config = config; } private Set<HostAndPort> parseHostAndPort() throws Exception { Set<HostAndPort> haps = new HashSet<HostAndPort>(); try { Properties prop = new Properties(); prop.load(this.addressConfig.getInputStream()); for (Object key : prop.keySet()) { if (!((String) key).startsWith(addressKeyPrefix)) { continue; } String val = (String) prop.get(key); boolean isIpPort = p.matcher(val).matches(); if (!isIpPort) { throw new IllegalArgumentException("ip 或 port 不合法"); } String[] ipAndPort = val.split(":"); HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1])); haps.add(hap); } } catch (IllegalArgumentException ex) { throw ex; } catch (Exception ex) { logger.error("解析 jedis 配置文件失败",ex); throw new Exception("解析 jedis 配置文件失败", ex); }finally{ return haps; } } }
JedisClusterHelper
package com.csair.csmbp.utiltool.redis; import org.springframework.util.SerializationUtils; import redis.clients.jedis.JedisCluster; public class JedisClusterHelper { private JedisCluster jedisCluster; private int timeOut; public JedisClusterHelper(JedisCluster jedisCluster){ this.jedisCluster = jedisCluster; } public void setTimeOut(int timeout) { this.timeOut = timeout; } public void saveOrUpdate(String key,Object obj,int timeout) { jedisCluster.setex(key.getBytes(), timeout, SerializationUtils.serialize(obj)); } public void saveOrUpdate(String key,Object obj) { jedisCluster.setex(key.getBytes(), this.timeOut , SerializationUtils.serialize(obj)); } public void saveOrUpdate(String key,String value,int timeout) { jedisCluster.setex(key, timeout, value); } public void saveOrUpdate(String key,String value) { jedisCluster.setex(key,this.timeOut , value); } public void incr(String key){ jedisCluster.incr(key); } public void expire(String key, int unixTime){ jedisCluster.expire(key, unixTime); } public void setnx(String key, String value){ jedisCluster.setnx(key, value); } public void hset(String key, String field, String value){ jedisCluster.hset(key, field, value); } public boolean exists(String key){ return jedisCluster.exists(key); } public <T> T getValue(String key ,Class<T> clazz){ return (T) SerializationUtils.deserialize(getValue(key.getBytes())); } public byte[] getValue(byte[] key){ return jedisCluster.get(key); } public String get(String key){ return jedisCluster.get(key); } public boolean del(String key){ boolean delFlag = false; jedisCluster.del(key); return delFlag; } }
调用示例
@Autowired private JedisClusterHelper jedisHelper; jedisHelper.saveOrUpdate(redisKey, obj, EXPIRED_SECOND);