jedis是Java的redis客户端实现,要使用jedis需要添加jedis的maven依赖:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.4.2</version>
</dependency>redis最简单的使用:Jedis jedis = new Jedis("localhost");//使用redis默认端口6379
jedis.set("foo", "bar");
String value = jedis.get("foo");但是jedis对象不是线程安全的,在多线程环境下会傻逼,所以官方提供了一个线程安全的连接池:JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");可以直接设置成静态的全局变量。因为一直使用spring,配置一个:<bean>
<property value="${redis.maxTotal}"/>
<property value="${redis.maxIdle}"/>
<property value="${redis.maxWaitMillis}"/>
<property value="true"/>
<property value="true"/>
</bean>
<bean>
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1" value="${redis.hostname}" />
<constructor-arg index="2" value="${redis.port}" />
</bean>ok,可以开始干活了:Jedis jedis = jedisPool.getResource();
try {
/// ... do stuff here ... for example
jedis.set("foo", "bar");
String foobar = jedis.get("foo");
jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike");
Set<String> sose = jedis.zrange("sose", 0, -1);
} catch (JedisConnectionException e) {
// returnBrokenResource when the state of the object is unrecoverable
if (null != jedis) {
pool.returnBrokenResource(jedis);
jedis = null;
}
} finally {
/// ... it's important to return the Jedis instance to the pool once you've finished using it
if (null != jedis)
pool.returnResource(jedis);
}
/// ... when closing your application:
pool.destroy();//如果不destroy的话,连接池中的connection将会一直连着,直到超时为止,所以在spring容器写一个destroy方法还是有必要的redis事务支持(transactions)。说白了就是:我要同时干好几件事,期间不能干别的,我就把这几件事放同一个事物里。Transaction t = jedis.multi();
t.set("aaa", "111");
t.set("bbb", "222");
t.exec();分布式客户端(ShardedJedis)我个人理解这东西就是个负载均衡,利用xxx哈希算法,均匀的把key存到不同redis服务器上jedisPoolConfig与上面的一样,第二个参数是redis服务器的列表<bean>
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1">
<list>
<bean>
<constructor-arg index="0" value="${redis.hostname}"/>
<constructor-arg index="1" value="${redis.port}"/>
</bean>
</list>
</constructor-arg>
</bean>使用:ShardedJedis jedis = pool.getResource();
jedis.set("a", "foo");
.... // do your work here
pool.returnResource(jedis);
.... // a few moments later
ShardedJedis jedis2 = pool.getResource();
jedis.set("z", "bar");
pool.returnResource(jedis);
pool.destroy();因为事务是在服务器端实现,而在分布式中,每批次的调用对象都可能访问不同的机器,所以,没法进行事务。import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import redis.clients.jedis.Jedis;
public class JedisDemo {
public void test1(){
Jedis redis = new Jedis ("192.168.10.64",6379);//连接redis
redis.auth("redis");//验证密码
/* ----------------------------------------------------------------------------------------------------------- */
/** KEY操作