1:
所需jar:jedis-2.1.0.jar:https://github.com/xetorthio/jedis https://github.com/xetorthio/jedis/downloads
spring-data-redis-1.1.9.RELEASE.jar:http://projects.spring.io/spring-data-redis/
2:属性文件:
# redis settings redis.pool.maxActive=1024 redis.pool.maxIdle=200 redis.pool.maxWait=1000 redis.pool.testOnBorrow=true redis.pool.testOnReturn=true redis.ip=192.168.6.146 redis.port=6379
3:Spring配置文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:c="http://www.springframework.org/schema/c" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd" default-lazy-init="true"> <description>Redis 缓存配置</description> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxActive" value="${redis.pool.maxActive}" /> <property name="maxIdle" value="${redis.pool.maxIdle}" /> <property name="maxWait" value="${redis.pool.maxWait}" /> <property name="testOnBorrow" value="${redis.pool.testOnBorrow}" /> <!-- <property name="testOnReturn" value="${redis.pool.testOnReturn}" /> --> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true"> <property name="hostName" value="${redis.ip}" /> <property name="port" value="${redis.port}" /> <property name="poolConfig" ref="jedisPoolConfig" /> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnectionFactory" /> <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref="jedisConnectionFactory" /> <!-- 启用缓存支持 --> <!-- turn on declarative caching --> <cache:annotation-driven /> <!-- declare Redis Cache Manager --> <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" c:template-ref="redisTemplate" /> </beans>
4:工具类:
import java.util.List;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.capitalbio.soft.core.utils.spring.SpringContextHolder;
public class ListOpsUtils {
public static StringRedisTemplate getStringRedisTemplate(){
return ((StringRedisTemplate)SpringContextHolder.getBean("stringRedisTemplate"));
}
/**
* 压栈
*
* @param key
* @param value
* @return
*/
public static Long push(String key, String value) {
return getStringRedisTemplate().opsForList().leftPush(key, value);
}
/**
* 出栈
*
* @param key
* @return
*/
public static String pop(String key) {
return getStringRedisTemplate().opsForList().leftPop(key);
}
/**
* 入队
*
* @param key
* @param value
* @return
*/
public static Long in(String key, String value) {
return getStringRedisTemplate().opsForList().rightPush(key, value);
}
/**
* 出队
*
* @param key
* @return
*/
public static String out(String key) {
return getStringRedisTemplate().opsForList().leftPop(key);
}
/**
* 栈/队列长
*
* @param key
* @return
*/
public static Long length(String key) {
return getStringRedisTemplate().opsForList().size(key);
}
/**
* 范围检索
*
* @param key
* @param start
* @param end
* @return
*/
public static List<String> range(String key, int start, int end) {
return getStringRedisTemplate().opsForList().range(key, start, end);
}
/**
* 移除
*
* @param key
* @param i
* @param value
*/
public static void remove(String key, long i, String value) {
getStringRedisTemplate().opsForList().remove(key, i, value);
}
/**
* 检索
*
* @param key
* @param index
* @return
*/
public static String index(String key, long index) {
return getStringRedisTemplate().opsForList().index(key, index);
}
/**
* 置值
*
* @param key
* @param index
* @param value
*/
public static void set(String key, long index, String value) {
getStringRedisTemplate().opsForList().set(key, index, value);
}
/**
* 裁剪
*
* @param key
* @param start
* @param end
*/
public static void trim(String key, long start, int end) {
getStringRedisTemplate().opsForList().trim(key, start, end);
}
}
5:单元测试:
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import com.capitalbio.soft.core.cache.redis.ListOpsUtils;
import com.capitalbio.soft.test.core.SpringTransactionalTestCase;
@ContextConfiguration(locations = { "/applicationContext.xml", "/applicationContext-redis.xml" })
public class ListOpsTest extends SpringTransactionalTestCase {
private String key = "queue";
@Before public void before() throws Exception {
System.out.println("------------IN---------------");
for (int i = 0; i < 5; i++) {
String uid = "u" + i;
System.out.println(uid);
ListOpsUtils.in(key, uid);
}
}
// 先进先出 - 队列 - FIFO (first in,first out)
@After public void after() {
// ------------OUT---------------
System.out.println("------------OUT---------------");
long length = ListOpsUtils.length(key);
for (long i = 0; i < length; i++) {
String uid = ListOpsUtils.out(key);
System.out.println(uid);
}
}
// 先进后出 - 栈 - LIFO(last in,first out)
@Test public void stack() {
// ------------PUSH---------------
String key = "stack";
int len = 5;
System.out.println("------------PUSH---------------");
for (int i = 0; i < len; i++) {
String uid = "u" + System.currentTimeMillis();
System.out.println(uid);
ListOpsUtils.push(key, uid);
}
long length = ListOpsUtils.length(key);
assertEquals(len, length);
// ------------POP---------------
System.out.println("------------POP---------------");
for (long i = 0; i < length; i++) {
String uid = ListOpsUtils.pop(key);
System.out.println(uid);
}
length = ListOpsUtils.length(key);
assertEquals(0, length);
}
@Test public void index() {
// -------------INDEX-------------
String value = ListOpsUtils.index(key, 3);
assertEquals("u3", value);
}
@Test
public void range() {
// -------------RANGE-------------
List<String> list = ListOpsUtils.range(key, 3, 5);
boolean result1 = list.contains("u3");
assertEquals(true, result1);
boolean result2 = list.contains("u1");
assertEquals(false, result2);
}
@Test
public void trim() {
// ------------TRIM---------------
List<String> list = ListOpsUtils.range(key, 3, 4);
ListOpsUtils.trim(key, 3, 4);
boolean result3 = list.contains("u1");
assertEquals(false, result3);
}
@Test
public void set() {
// ------------SET-----------------
List<String> list = ListOpsUtils.range(key, 3, 5);
ListOpsUtils.set(key, 4, "ux4");
boolean result4 = list.contains("u4");
assertEquals(true, result4);
}
@Test
public void remove() {
// ------------REMOVE-----------------
ListOpsUtils.remove(key, 4, "u4");
String value = ListOpsUtils.index(key, 4);
assertEquals(null, value);
}
}
6:基本用法单元测试:
import java.io.Serializable;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import redis.clients.jedis.Jedis;
import com.capitalbio.soft.test.core.SpringTransactionalTestCase;
@ContextConfiguration(locations = { "/applicationContext.xml", "/applicationContext-redis.xml" })
public class JedisRedisTest extends SpringTransactionalTestCase {
private Logger logger = LoggerFactory.getLogger(getClass());
// @Autowired private ShardedJedisPool jedisPool;
@Resource(name="redisTemplate") private RedisTemplate<Serializable,Serializable> redisTemplate;
// @Resource(name="stringRedisTemplate") private StringRedisTemplate stringRedisTemplate;
@Test
public void testSimple() {
Jedis jedis = new Jedis("10.11.20.140");
String keys = "name";
// 存数据
jedis.set(keys, "snowolf");
// 取数据
String value = jedis.get(keys);
// 删数据
jedis.del(keys);
System.out.println(value);
}
/*
@Test
public void testJedisSpring() {
String key = "redis-jedis-integration";
ShardedJedis jedis = jedisPool.getResource();
String keyRet = jedis.set(key, "yes! it's wonderfull!"); // 将值保存到redis服务器
String valRet = jedis.get(key); // 从redis服务器获取值
jedis.del(key);
// 释放对象池
jedisPool.returnResource(jedis);
logger.debug("{} : {}", keyRet, valRet);
}
*/
@Test public void testJedisRedisTemplateGetSetDel() {
final String key = "test-redis-key";
final String val = "test-redis-val";
final byte[] serialKey = redisTemplate.getStringSerializer().serialize(key);
final byte[] serialVal = redisTemplate.getStringSerializer().serialize(val);
String ret = redisTemplate.execute(new RedisCallback<String>() {
@Override public String doInRedis(RedisConnection connection) throws DataAccessException {
// 普通 getset 操作
connection.set(serialKey, serialVal);
if(connection.exists(serialKey)) {
byte[] byteVal = connection.get(serialKey);
String retVal = redisTemplate.getStringSerializer().deserialize(byteVal);
long delCount = connection.del(serialKey);
return retVal + " ," + Long.toString(delCount) + " " + connection.exists(serialKey);
}
return null;
}
});
logger.debug("{}",ret);
}
@Test
public void testJedisRedisTemplatehMSet() {
final String key = "test-redis-key";
final String val = "test-redis-val";
final byte[] serialKey = redisTemplate.getStringSerializer().serialize(key);
final byte[] serialVal = redisTemplate.getStringSerializer().serialize(val);
final byte[] subSerialKey = redisTemplate.getStringSerializer().serialize("sub" + key);
final byte[] subSerialVal = redisTemplate.getStringSerializer().serialize("sub" + val);
redisTemplate.execute(new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
// HashTable操作
// 设置
BoundHashOperations<Serializable, byte[], byte[]> boundHashOperations = redisTemplate.boundHashOps(serialKey);
boundHashOperations.put(subSerialKey, subSerialVal);
boundHashOperations.put(serialKey, serialVal);
logger.debug("{}",connection.hMGet(serialVal, subSerialKey,serialVal).size());
logger.debug("{}",connection.hMGet(serialVal, subSerialKey,serialVal).get(0));
connection.hMSet(serialKey, boundHashOperations.entries());
// 获取
if(connection.exists(serialKey)) {
List<byte[]> value = connection.hMGet(serialKey, subSerialKey,serialKey);
String subRetVal = redisTemplate.getStringSerializer().deserialize(value.get(0));
String retVal = redisTemplate.getStringSerializer().deserialize(value.get(1));
logger.debug("{} : {}",subRetVal,retVal);
}
// 删除
long delCount = connection.del(serialKey);
logger.debug("del: {} {} {}",delCount,connection.exists(serialKey),connection.hMGet(serialKey, subSerialKey,serialKey).size());
return null;
}
});
}
@Test public void testJedisRedisTemplateListOps() {
redisTemplate.execute(new RedisCallback<Object>() {
@Override public Object doInRedis(RedisConnection connection) throws DataAccessException {
return null;
}
});
}
}
7:监控:Angel
https://github.com/litiebiao2012/redis-monitor