首先说一下我的包
commons-pool2-2.0.jar
jedis-2.7.2.jar
spring-data-redis-1.4.2.RELEASE.jar
tomcat-redis-session-manager1.2.jar
属性文件 redis.properties
属性文件 address1=127.0.0.1:7002 address2=127.0.0.1:7001 address3=127.0.0.1:7000 address4=127.0.0.1:7003 address5=127.0.0.1:7004 address6=127.0.0.1:7005
然后是配置文件 redis-context.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- 连接池的配置 --> <bean name="genericObjectPoolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig"> <property name="maxWaitMillis" value="-1" /> <property name="maxTotal" value="1000" /> <property name="minIdle" value="8" /> <property name="maxIdle" value="100" /> </bean> <bean id="jedisClusterFactory" class="com.hanwei.its.itoss.dao.redis.JedisClusterFactory"> <property name="addressConfig"> <value>classpath:conf/redis.properties</value> <value>/conf/redis.properties</value> </property> <property name="addressKeyPrefix" value="address" /> <!-- 属性文件里 key的前缀 --> <property name="timeout" value="300000" /> <property name="maxRedirections" value="6" /> <property name="genericObjectPoolConfig" ref="genericObjectPoolConfig" /> </bean> </beans>
在 Spring MVC文件中引入redis 配置文件
<!-- 加载redis 配置文件 --> <import resource="redis-context.xml"/>
上代码
package com.hanwei.its.itoss.dao.redis; import java.io.InputStream; 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.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.stereotype.Repository; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; @Repository(value="jedisClusterFactory") public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean{ private Resource addressConfig; private String addressKeyPrefix ; private JedisCluster jedisCluster; private String timeout ; private String maxRedirections ; private GenericObjectPoolConfig genericObjectPoolConfig ; public GenericObjectPoolConfig getGenericObjectPoolConfig(){ GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig(); genericObjectPoolConfig.setMaxWaitMillis(1000); genericObjectPoolConfig.setMaxTotal(20000); genericObjectPoolConfig.setMaxIdle(20); genericObjectPoolConfig.setTestOnBorrow(true); return genericObjectPoolConfig; } private Pattern p = Pattern.compile("^.+[:]\d{1,5}\s*$"); @Override public JedisCluster getObject() throws Exception { afterPropertiesSet(); return jedisCluster; } @Override public Class<? extends JedisCluster> getObjectType() { return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class); } @Override public boolean isSingleton() { return true; } private Set<HostAndPort> parseHostAndPort() throws Exception { try { Properties prop = new Properties(); //读取属性文件 PS:我的项目有问题,Spring 注入不进去 不知道咋回事,所以我就用了这种方式 给redis 做了初始化 InputStream in = getClass().getClassLoader().getResourceAsStream("/conf/redis.properties"); prop.load(in); Set<HostAndPort> haps = new HashSet<HostAndPort>(); if(addressKeyPrefix == null){ addressKeyPrefix ="address"; } 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); } return haps; } catch (IllegalArgumentException ex) { throw ex; } catch (Exception ex) { throw new Exception("解析 jedis 配置文件失败", ex); } } @Override public void afterPropertiesSet() throws Exception { Set<HostAndPort> haps = this.parseHostAndPort(); if(genericObjectPoolConfig == null){ genericObjectPoolConfig = getGenericObjectPoolConfig(); } jedisCluster = new JedisCluster(haps,genericObjectPoolConfig); } public void setAddressConfig(Resource addressConfig) { this.addressConfig = addressConfig; } public void setTimeout(String timeout) { this.timeout = timeout; } public void setMaxRedirections(String maxRedirections) { this.maxRedirections = maxRedirections; } public void setAddressKeyPrefix(String addressKeyPrefix) { this.addressKeyPrefix = addressKeyPrefix; } public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) { this.genericObjectPoolConfig = genericObjectPoolConfig; } }
//实体类
package com.hanwei.its.itoss.model.redis; import org.szopen.core.model.BaseModel; public class Member extends BaseModel{ /** * */ private static final long serialVersionUID = -1959528436584592183L; private String id; private String nickname; private Object val; private int index; public Member(){} public Member(String id, String nickname){ this.setId(id); this.setNickname(nickname); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public Object getVal() { return val; } public void setVal(Object val) { this.val = val; } }
剩下的就很无聊了
在dao层注入上面这个 Factory
需要注意的是 我这个 jedisClusterFactory 每次使用完毕都有执行close()方法 使用前都要GET jedisClusterFactory.getObject(); 到新的对象
package com.hanwei.its.itoss.dao.redis.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.ShardedJedis;
import com.hanwei.its.itoss.dao.redis.JedisClusterFactory;
import com.hanwei.its.itoss.dao.redis.MemberDao;
import com.hanwei.its.itoss.model.redis.Member;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;
@Repository(value="memberDao")
@Component
public class MemberDaoImpl implements MemberDao{
@Autowired
@Qualifier("jedisClusterFactory")
private JedisClusterFactory jedisClusterFactory;
public void CloseJedis(ShardedJedis jedis){
if(jedis != null){
jedis.close();
}
}
/**
* 添加对象
* @throws Exception
*/
@Override
public boolean add(final Member member) {
JedisCluster JedisCluster ;
try {
JedisCluster = jedisClusterFactory.getObject();
JedisCluster.sadd(member.getId(), member.getVal().toString());
JedisCluster.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
/**
* 删除对象 ,依赖key
* @throws Exception
*/
@Override
public void delete(String key) {
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
JedisCluster.del(key);
JedisCluster.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 修改对象
* @throws Exception
*/
@Override
public boolean update(final Member member) {
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
JedisCluster.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
/**
* 根据key获取对象
*/
@Override
public Member get(final String keyId) {
Member member;
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
Set<String> smembers = JedisCluster.smembers(keyId);
member = new Member();
member.setId(keyId);
member.setVal(smembers);
JedisCluster.close();
return member;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void sadd(Member member) {
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
JedisCluster.sadd(member.getId(), member.getVal().toString());
JedisCluster.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void set(Member member) {
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
JedisCluster.set(member.getId(), member.getVal().toString());
JedisCluster.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Member getForSet(String key) {
Member member;
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
String val = JedisCluster.get(key);
member = new Member();
member.setId(key);
member.setVal(val);
JedisCluster.close();
return member;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取所有List
*/
@Override
public List<Member> getListAll(String key){
List<Member> memberList = new ArrayList<Member>();
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
List<String> val = JedisCluster.lrange(key, 0, -1);
for (String string : val) {
Member member = new Member();
member.setVal(string);
member.setId(key);
memberList.add(member);
}
JedisCluster.close();
return memberList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取长度
*/
@Override
public int getLength(String key) {
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
String val = JedisCluster.get(key);
JedisCluster.close();
return Integer.parseInt(val);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 获取列表指定下标的值
*/
@Override
public Member getIndex(int index,String key) {
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
String val = JedisCluster.lindex(key, index);
Member member = new Member();
member.setVal(val);
member.setId(key);
member.setIndex(index);
JedisCluster.close();
return member;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 修改列表中单个值
*/
@Override
public void updateIndex(int index, Member member) {
String key = member.getId();
Object val2 = member.getVal();
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
String val = JedisCluster.lset(key, index, val2.toString());
JedisCluster.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除列表指定下标的值
*/
@Override
public Long removeIndex(int index, Member member) {
String key = member.getId();
Object val2 = member.getVal();
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
Long val = JedisCluster.lrem(key, index, val2.toString());
JedisCluster.close();
return val;
} catch (Exception e) {
e.printStackTrace();
}
return (long) 0;
}
/**
* 新增
*/
@Override
public Long appendList(Member member) {
String key = member.getId();
Object val2 = member.getVal();
try {
JedisCluster JedisCluster = jedisClusterFactory.getObject();
Long val = JedisCluster.lpush(key, val2.toString());
JedisCluster.close();
return val;
} catch (Exception e) {
e.printStackTrace();
}
return (long) 0;
}
}