Redis客户端
一、Java客户端:Jedis
1.获取Jedis
Jedis是什么?
Maven依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
Jedis直连
#1.生成一个Jedis对象,这个对象负责和指定Redis节点进行通信
Jedis jedis = new Jedis("127.0.0.1",6379);
#2.jedis操作set
jedis.set("hello","world");
#3.jedis执行get操作,value=“world”
String value = jedis.get("hello");
Jedis(String host,int port,int connectionTimeout,int soTimeout)
host:Redis节点的所在机器的IP
port:Redis节点的端口
connectionTimecout:客户端连接超时
soTimeout:客户端读写超时
简单使用
1.string
//输出结果ok
jedis.set("hello","world");
//输出结果:world
jedis.get("hello")
//输出结果:1
jsdis.incr("counter");
2.hash
jedis.hset("myhash","f1","v1");
jedis.hset("myhash","f2","v2");
//输出结果{f1=f2,f2=v2}
jedis.hgetAll("myhash");
3.list
jedis.rpush("mylist","1");
jedis.rpush("mylist","2");
jedis.rpush("mylist","3");
//输出结果:[1,2,3]
jedis.lrange("mylist",0,-1);
4.set
jedis.sadd("myset","a");
jedis.sadd("myset","b");
jedis.sadd("myset","a");
//输出结果:[b,a]
jedis.smembers("myset");
5.zset
jedis.zadd("myset",99,"tom");
jedis.zadd("myset",66,"peter");
jedis.zadd("myset",33,"james");
//输出结果:[[["james"],33.0],[["pater"],66.0],[["tom"],99.0]]
jedis.zrangeWithScorces("myzset",0,-1);
2.Jedis连接池
(1)Jedis直连

(2)Jedis连接池

(3)方案对比

(4)JedisPool使用
初始化Jedis连接池,通常来讲JedisPool是单例的。GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
JedisPool jedisPool = new JedisPool(poolConfig,"127.0.0.1",6379);
Jedis jedis = null;
try{
//1.从连接池获取jedis对象
jedis = jedisPool.getResource();
//2.执行操作
jedis.set("hello","world");
}catch(Exception e){
e.printStackTrace();
}
finally{
if(jedis!=null)
//如果使用JedisPool,close操作不是关闭连接,代表归还连接池
jedis.close();
}
二、Python客户端:redis-py
1.获取redis-py
(1)pip install redis
(2)easy_install redis
(3)源码安装
wget https://github.com/andymccurdy/redis-py/archive/2.10.5.zip
unzip redis-2.10.5.zip
cd redis-2.10.5
#安装redis-py
sudo python setup.py install
import redis
client = redis.StrictRedis(host='127.0.0.1',port=6379)
key = "hello"
setResult = client.set(key,"python-redis")
print(setResult)
vaule = client.get(key)
print("key:"+key+",value:"+vaule)
使用同上
网友评论