redis在java中的使用(摘自多篇文章,通过例子熟悉如何使用jedis)
共四篇文章:
以下部分转自http://blog.csdn.net/top_code/article/details/51292240
版权声明:本文为博主原创文章,未经博主允许不得转载。
概述
Redis是一个开源的、高效的key-value存储系统,也是nosql中的最常见的一种。Redis非常适合用来做缓存系统,关于redis的详细介绍可以查看Redis官方documentation。
Redis支持多语言的调用,官方推荐的Java版客户端是Jedis,它非常强大和稳定,支持事务、管道及有Jedis自身实现。我们对Redis数据的操作,都可以通过Jedis来完成。
使用教程
1、配置maven依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
Jedis 线程安全问题
首先,需要注意的是单个的Jedis 实例不是线程安全,在多线程环境下你应该使用JedisPool。
using Jedis in a multithreaded environment
You shouldn’t use the same instance from different threads because you’ll have strange errors. And sometimes creating lots of Jedis instances is not good enough because it means lots of sockets and connections, which leads to strange errors as well. A single Jedis instance is not threadsafe! To avoid these problems, you should use JedisPool, which is a threadsafe pool of network connections. You can use the pool to reliably create several Jedis instances, given you return the Jedis instance to the pool when done. This way you can overcome those strange errors and achieve great performance.
初始化pool
JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
JedisPool 是线程安全的,你可以将它作为一个静态变量保存起来。
为了保证Jedis 一定会被关闭,我们可以使用try-finally语句,如下:
Jedis jedis = null;
try {
jedis = pool.getResource();
/// ... 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);
} finally {
if (jedis != null) {
jedis.close();
}
}
/// ... when closing your application:
pool.destroy();
在介绍Jedis API使用之前,我们先使用单例模式对JedisPool 做一个封装,代码如下:
package com.ricky.codelab.redis.sample.pool;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import com.ricky.codelab.redis.sample.util.PropertyUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisPoolManager {
private volatile static JedisPoolManager manager;
private final JedisPool pool;
private JedisPoolManager() {
try {
//加载redis配置
Properties props = PropertyUtils.load("redis.properties");
// 创建jedis池配置实例
JedisPoolConfig config = new JedisPoolConfig();
// 设置池配置项值
String maxTotal = props.getProperty("redis.pool.maxTotal", "4");
config.setMaxTotal(Integer.parseInt(maxTotal));
String maxIdle = props.getProperty("redis.pool.maxIdle", "4");
config.setMaxIdle(Integer.parseInt(maxIdle));
String minIdle = props.getProperty("redis.pool.minIdle", "1");
config.setMinIdle(Integer.parseInt(minIdle));
String maxWaitMillis = props.getProperty("redis.pool.maxWaitMillis", "1024");
config.setMaxWaitMillis(Long.parseLong(maxWaitMillis));
String testOnBorrow = props.getProperty("redis.pool.testOnBorrow", "true");
config.setTestOnBorrow("true".equals(testOnBorrow));
String testOnReturn = props.getProperty("redis.pool.testOnReturn", "true");
config.setTestOnReturn("true".equals(testOnReturn));
String server = props.getProperty("redis.server");
if(StringUtils.isEmpty(server)){
throw new IllegalArgumentException("JedisPool redis.server is empty!");
}
String[] host_arr = server.split(",");
if(host_arr.length>1){
throw new IllegalArgumentException("JedisPool redis.server length > 1");
}
String[] arr = host_arr[0].split(":");
// 根据配置实例化jedis池
System.out.println("***********init JedisPool***********");
System.out.println("host->"+arr[0]+",port->"+arr[1]);
pool = new JedisPool(config, arr[0], Integer.parseInt(arr[1]));
} catch (IOException e) {
throw new IllegalArgumentException("init JedisPool error", e);
}
}
public static JedisPoolManager getMgr() {
if (manager == null) {
synchronized (JedisPoolManager.class) {
if (manager == null) {
manager = new JedisPoolManager();
}
}
}
return manager;
}
public Jedis getResource() {
return pool.getResource();
}
public void destroy() {
// when closing your application:
pool.destroy();
}
public void close() {
pool.close();
}
}
redis.properties 如下:
# Redis server ip and port
redis.server=172.18.19.208:6379
# Redis pool
redis.pool.maxTotal=20
redis.pool.maxIdle=10
redis.pool.minIdle=1
redis.pool.maxWaitMillis=60000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
有了JedisPoolManager类,操作Jedis的模板代码简化如下:
Jedis jedis = null;
try {
jedis = JedisPoolManager.getMgr().getResource();
// jedis.auth("hello");
} finally {
if (jedis != null) {
jedis.close();
}
}
/// ... when closing your application:
JedisPoolManager.getMgr().destroy();
基本用法
package com.ricky.codelab.redis.sample;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.ricky.codelab.redis.sample.pool.JedisPoolManager;
import redis.clients.jedis.Jedis;
public class RedisDemo {
public static void main(String[] args) {
Jedis jedis = null;
try {
jedis = JedisPoolManager.getMgr().getResource();
// jedis.auth("hello");
//simple key-value
jedis.set("redis", "myredis");
System.out.println(jedis.get("redis"));
jedis.append("redis", "yourredis");
jedis.append("mq", "RabbitMQ");
//incr
String pv = jedis.set("pv", "0");
System.out.println("pv:"+pv);
jedis.incr("pv");
jedis.incrBy("pv", 10);
System.out.println("pv:"+pv);
//mset
jedis.mset("firstName", "ricky", "lastName", "Fung");
System.out.println(jedis.mget("firstName", "lastName"));
//map
Map<String,String> cityMap = new HashMap<String,String>();
cityMap.put("beijing", "1");
cityMap.put("shanghai", "2");
jedis.hmset("city", cityMap);
System.out.println(jedis.hget("city", "beijing"));
System.out.println(jedis.hlen("city"));
System.out.println(jedis.hmget("city", "beijing","shanghai"));
//list
jedis.lpush("hobbies", "reading");
jedis.lpush("hobbies", "basketball");
jedis.lpush("hobbies", "shopping");
List<String> hobbies = jedis.lrange("hobbies", 0, -1);
System.out.println("hobbies:"+hobbies);
jedis.del("hobbies");
//set
jedis.sadd("name", "ricky");
jedis.sadd("name", "kings");
jedis.sadd("name", "demon");
System.out.println("size:"+jedis.scard("name"));
System.out.println("exists:"+jedis.sismember("name", "ricky"));
System.out.println(String.format("all members: %s", jedis.smembers("name")));
System.out.println(String.format("rand member: %s", jedis.srandmember("name")));
//remove
jedis.srem("name", "demon");
//hset
jedis.hset("address", "country", "CN");
jedis.hset("address", "province", "BJ");
jedis.hset("address", "city", "Beijing");
jedis.hset("address", "district", "Chaoyang");
System.out.println("city:"+jedis.hget("address", "city"));
System.out.println("keys:"+jedis.hkeys("address"));
System.out.println("values:"+jedis.hvals("address"));
//zadd
jedis.zadd("gift", 0, "car");
jedis.zadd("gift", 0, "bike");
Set<String> gift = jedis.zrange("gift", 0, -1);
System.out.println("gift:"+gift);
} finally {
if (jedis != null) {
jedis.close();
}
}
/// ... when closing your application:
JedisPoolManager.getMgr().destroy();
}
}
另外,我们除了可以使用redis.clients.jedis.Jedis.set(String key, String value) insert string之外,还可以使用redis.clients.jedis.BinaryJedis.set(byte[] key, byte[] value) 保存我们自定义的POJO类,代码如下:
package com.ricky.codelab.redis.sample;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import com.ricky.codelab.redis.sample.pool.JedisPoolManager;
import redis.clients.jedis.Jedis;
public class RedisPojoDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Jedis jedis = null;
try {
jedis = JedisPoolManager.getMgr().getResource();
Person person = new Person("Ricky", 27);
//序列化
byte[] byteArray = serialize(person);
//set
jedis.set("Ricky".getBytes(), byteArray);
//get
byteArray = jedis.get("Ricky".getBytes());
//反序列化
person = deserialize(byteArray);
System.out.println(person);
} finally {
if (jedis != null) {
jedis.close();
}
}
/// ... when closing your application:
JedisPoolManager.getMgr().destroy();
}
public static Person deserialize(byte[] byteArray) throws ClassNotFoundException, IOException{
ObjectInputStream ois = null;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
ois = new ObjectInputStream(bais);
return (Person) ois.readObject();
} finally {
ois.close();
}
}
public static byte[] serialize(Person person) throws IOException{
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(person);
oos.flush();
return baos.toByteArray();
} finally {
oos.close();
baos.close();
}
}
}
class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
这里需要用到Java的序列化机制,我们使用的Java内置的序列化机制,当然也可以使用第三方提供的高效序列化机制,例如:Kryo、Hessian、protostuff等。
高级用法
1、事务(Transactions)
所谓事务,即一个连续操作,是否执行是一个事务,要么完成,要么失败,没有中间状态。
而redis的事务很简单,他主要目的是保障,一个client发起的事务中的命令可以连续的执行,而中间不会插入其他client的命令,也就是事务的连贯性。
Jedis jedis = null;
try {
jedis = JedisPoolManager.getMgr().getResource();
jedis.auth("password");
Transaction t = jedis.multi();
t.set("foo", "bar");
t.exec();
} finally {
if (jedis != null) {
jedis.close();
}
}
/// ... when closing your application:
JedisPoolManager.getMgr().destroy();
我们调用jedis.watch(…)方法来监控key,如果调用后key值发生变化,则整个事务会执行失败。另外,事务中某个操作失败,并不会回滚其他操作。这一点需要注意。还有,我们可以使用discard()方法来取消事务。
如果某些方法有返回值,你可以这么做:
Transaction t = jedis.multi();
t.set("fool", "bar");
Response<String> result1 = t.get("fool");
t.zadd("foo", 1, "barowitch"); t.zadd("foo", 0, "barinsky"); t.zadd("foo", 0, "barikoviev");
Response<Set<String>> sose = t.zrange("foo", 0, -1); // get the entire sortedset
t.exec(); // dont forget it
String foolbar = result1.get(); // use Response.get() to retrieve things from a Response
int soseSize = sose.get().size(); // on sose.get() you can directly call Set methods!
// List<Object> allResults = t.exec(); // you could still get all results at once, as before
2、管道(Pipelining)
Sometimes you need to send a bunch of different commands. A very cool way to do that, and have better performance than doing it the naive way, is to use pipelining. This way you send commands without waiting for response, and you actually read the responses at the end, which is faster.
Pipeline p = jedis.pipelined();
p.set("fool", "bar");
p.zadd("foo", 1, "barowitch"); p.zadd("foo", 0, "barinsky"); p.zadd("foo", 0, "barikoviev");
Response<String> pipeString = p.get("fool");
Response<Set<String>> sose = p.zrange("foo", 0, -1);
p.sync();
int soseSize = sose.get().size();
Set<String> setBack = sose.get();
3、Publish/Subscribe
To subscribe to a channel in Redis, create an instance of JedisPubSub and call subscribe on the Jedis instance:
class MyListener extends JedisPubSub {
public void onMessage(String channel, String message) {
}
public void onSubscribe(String channel, int subscribedChannels) {
}
public void onUnsubscribe(String channel, int subscribedChannels) {
}
public void onPSubscribe(String pattern, int subscribedChannels) {
}
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
public void onPMessage(String pattern, String channel,
String message) {
}
}
MyListener l = new MyListener();
jedis.subscribe(l, "foo");
4、分布式Redis(ShardedJedis)
1.Define your shards:
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si = new JedisShardInfo("localhost", 6379);
si.setPassword("foobared");
shards.add(si);
si = new JedisShardInfo("localhost", 6380);
si.setPassword("foobared");
shards.add(si);
2.a) Direct connection:
ShardedJedis jedis = new ShardedJedis(shards);
jedis.set("a", "foo");
jedis.disconnect();
2.b) Pooled connection:
ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards);
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();
最后,我对ShardedJedisPool 也做了一个简单封装,从redis_cluster.properties 文件中获取配置信息并做初始化,代码如下:
package com.ricky.codelab.redis.sample.pool;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import com.ricky.codelab.redis.sample.util.PropertyUtils;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
public class ShardedJedisPoolManager {
private volatile static ShardedJedisPoolManager manager;
private final ShardedJedisPool shardedJedisPool;
private ShardedJedisPoolManager() {
try {
Properties props = PropertyUtils.load("redis_cluster.properties");
// 创建jedis池配置实例
JedisPoolConfig config = new JedisPoolConfig();
// 设置池配置项值
String maxTotal = props.getProperty("redis.pool.maxTotal", "4");
config.setMaxTotal(Integer.parseInt(maxTotal));
String maxIdle = props.getProperty("redis.pool.maxIdle", "4");
config.setMaxIdle(Integer.parseInt(maxIdle));
String minIdle = props.getProperty("redis.pool.minIdle", "1");
config.setMinIdle(Integer.parseInt(minIdle));
String maxWaitMillis = props.getProperty("redis.pool.maxWaitMillis", "1024");
config.setMaxWaitMillis(Long.parseLong(maxWaitMillis));
String testOnBorrow = props.getProperty("redis.pool.testOnBorrow", "true");
config.setTestOnBorrow("true".equals(testOnBorrow));
String testOnReturn = props.getProperty("redis.pool.testOnReturn", "true");
config.setTestOnReturn("true".equals(testOnReturn));
String server = props.getProperty("redis.server");
if(StringUtils.isEmpty(server)){
throw new IllegalArgumentException("ShardedJedisPool redis.server is empty!");
}
String[] host_arr = server.split(",");
List<JedisShardInfo> list = new ArrayList<JedisShardInfo>(host_arr.length);
for(String host : host_arr){
String[] arr = host.split(":");
System.out.println("init ShardedJedisPool host->"+arr[0]+",port->"+arr[1]);
JedisShardInfo jedisShardInfo = new JedisShardInfo(
arr[0], Integer.parseInt(arr[1]));
jedisShardInfo.setPassword("password");
list.add(jedisShardInfo);
}
//根据配置文件,创建shared池实例
System.out.println("***********init ShardedJedisPool***********");
shardedJedisPool = new ShardedJedisPool(config, list);
} catch (IOException e) {
throw new IllegalArgumentException("init ShardedJedisPool error", e);
}
}
public static ShardedJedisPoolManager getMgr() {
if (manager == null) {
synchronized (ShardedJedisPoolManager.class) {
if (manager == null) {
manager = new ShardedJedisPoolManager();
}
}
}
return manager;
}
public ShardedJedis getResource() {
return shardedJedisPool.getResource();
}
public void destroy() {
// when closing your application:
shardedJedisPool.destroy();
}
public void close() {
shardedJedisPool.close();
}
}
redis_cluster.properties
# Redis server ip and port
redis.server=172.18.19.206:6379,172.18.19.207:6379,172.18.19.208:6379
password=12345
# Redis pool
redis.pool.maxTotal=20
redis.pool.maxIdle=10
redis.pool.minIdle=1
redis.pool.maxWaitMillis=60000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
点此下载完整示例代码
参考资料:
https://github.com/xetorthio/jedis/wiki
以下部分转自:http://www.importnew.com/19321.html
通过前一篇《redis的简单使用》的简单介绍,本篇主要阐述Jedis对redis的五大类型的操作:字符串、列表、散列、集合、有序集合。
JedisUtil
这里的测试用例采用junit4进行运行,准备代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
private static final String ipAddr = "10.10.195.112" ; private static final int port = 6379 ; private static Jedis jedis= null ; @BeforeClass public static void init() { jedis = JedisUtil.getInstance().getJedis(ipAddr, port); } @AfterClass public static void close() { JedisUtil.getInstance().closeJedis(jedis,ipAddr, port); } |
其中JedisUtil是对jedis做的简单封装,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
import org.apache.log4j.Logger; import java.util.HashMap; import java.util.Map; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisUtil { private Logger logger = Logger.getLogger( this .getClass().getName()); private JedisUtil(){} private static class RedisUtilHolder{ private static final JedisUtil instance = new JedisUtil(); } public static JedisUtil getInstance(){ return RedisUtilHolder.instance; } private static Map<String,JedisPool> maps = new HashMap<String,JedisPool>(); private static JedisPool getPool(String ip, int port){ String key = ip+ ":" +port; JedisPool pool = null ; if (!maps.containsKey(key)) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxActive(RedisConfig.MAX_ACTIVE); config.setMaxIdle(RedisConfig.MAX_IDLE); config.setMaxWait(RedisConfig.MAX_WAIT); config.setTestOnBorrow( true ); config.setTestOnReturn( true ); pool = new JedisPool(config,ip,port,RedisConfig.TIMEOUT); maps.put(key, pool); } else { pool = maps.get(key); } return pool; } public Jedis getJedis(String ip, int port) { Jedis jedis = null ; int count = 0 ; do { try { jedis = getPool(ip,port).getResource(); } catch (Exception e) { logger.error( "get redis master1 failed!" ,e); getPool(ip,port).returnBrokenResource(jedis); } } while (jedis == null && count<RedisConfig.RETRY_NUM); return jedis; } public void closeJedis(Jedis jedis, String ip, int port){ if (jedis != null ) { getPool(ip,port).returnResource(jedis); } } } public class RedisConfig { //可用连接实例的最大数目,默认值为8; //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。 public static int MAX_ACTIVE = 1024 ; //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。 public static int MAX_IDLE = 200 ; //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException; public static int MAX_WAIT = 10000 ; public static int TIMEOUT = 10000 ; public static int RETRY_NUM = 5 ; } |
键操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@Test public void testKey() throws InterruptedException { System.out.println( "清空数据:" +jedis.flushDB()); System.out.println( "判断某个键是否存在:" +jedis.exists( "username" )); System.out.println( "新增<'username','zzh'>的键值对:" +jedis.set( "username" , "zzh" )); System.out.println(jedis.exists( "name" )); System.out.println( "新增<'password','password'>的键值对:" +jedis.set( "password" , "password" )); System.out.print( "系统中所有的键如下:" ); Set<String> keys = jedis.keys( "*" ); System.out.println(keys); System.out.println( "删除键password:" +jedis.del( "password" )); System.out.println( "判断键password是否存在:" +jedis.exists( "password" )); System.out.println( "设置键username的过期时间为5s:" +jedis.expire( "username" , 5 )); TimeUnit.SECONDS.sleep( 2 ); System.out.println( "查看键username的剩余生存时间:" +jedis.ttl( "username" )); System.out.println( "移除键username的生存时间:" +jedis.persist( "username" )); System.out.println( "查看键username的剩余生存时间:" +jedis.ttl( "username" )); System.out.println( "查看键username所存储的值的类型:" +jedis.type( "username" )); } |
输出结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
清空数据:OK 判断某个键是否存在: false 新增< 'username' , 'zzh' >的键值对:OK false 新增< 'password' , 'password' >的键值对:OK 系统中所有的键如下:[username, password] 删除键password: 1 判断键password是否存在: false 设置键username的过期时间为5s: 1 查看键username的剩余生存时间: 3 移除键username的生存时间: 1 查看键username的剩余生存时间:- 1 查看键username所存储的值的类型:string |
字符串操作
在Redis里面,字符串可以存储三种类型的值:
- 字节串(byte string)
- 整数
- 浮点数
字节串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
@Test public void testString() throws InterruptedException { jedis.flushDB(); System.out.println( "===========增加数据===========" ); System.out.println(jedis.set( "key1" , "value1" )); System.out.println(jedis.set( "key2" , "value2" )); System.out.println(jedis.set( "key3" , "value3" )); System.out.println( "删除键key2:" +jedis.del( "key2" )); System.out.println( "获取键key2:" +jedis.get( "key2" )); System.out.println( "修改key1:" +jedis.set( "key1" , "value1Changed" )); System.out.println( "获取key1的值:" +jedis.get( "key1" )); System.out.println( "在key3后面加入值:" +jedis.append( "key3" , "End" )); System.out.println( "key3的值:" +jedis.get( "key3" )); System.out.println( "增加多个键值对:" +jedis.mset( "key01" , "value01" , "key02" , "value02" , "key03" , "value03" )); System.out.println( "获取多个键值对:" +jedis.mget( "key01" , "key02" , "key03" )); System.out.println( "获取多个键值对:" +jedis.mget( "key01" , "key02" , "key03" , "key04" )); System.out.println( "删除多个键值对:" +jedis.del( new String[]{ "key01" , "key02" })); System.out.println( "获取多个键值对:" +jedis.mget( "key01" , "key02" , "key03" )); jedis.flushDB(); System.out.println( "===========新增键值对防止覆盖原先值==============" ); System.out.println(jedis.setnx( "key1" , "value1" )); System.out.println(jedis.setnx( "key2" , "value2" )); System.out.println(jedis.setnx( "key2" , "value2-new" )); System.out.println(jedis.get( "key1" )); System.out.println(jedis.get( "key2" )); System.out.println( "===========新增键值对并设置有效时间=============" ); System.out.println(jedis.setex( "key3" , 2 , "value3" )); System.out.println(jedis.get( "key3" )); TimeUnit.SECONDS.sleep( 3 ); System.out.println(jedis.get( "key3" )); System.out.println( "===========获取原值,更新为新值==========" ); //GETSET is an atomic set this value and return the old value command. System.out.println(jedis.getSet( "key2" , "key2GetSet" )); System.out.println(jedis.get( "key2" )); System.out.println( "获得key2的值的字串:" +jedis.getrange( "key2" , 2 , 4 )); } |
输出结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
===========增加数据=========== OK OK OK 删除键key2: 1 获取键key2: null 修改key1:OK 获取key1的值:value1Changed 在key3后面加入值: 9 key3的值:value3End 增加多个键值对:OK 获取多个键值对:[value01, value02, value03] 获取多个键值对:[value01, value02, value03, null ] 删除多个键值对: 2 获取多个键值对:[ null , null , value03] ===========新增键值对防止覆盖原先值============== 1 1 0 value1 value2 ===========新增键值对并设置有效时间============= OK value3 null ===========获取原值,更新为新值========== value2 key2GetSet 获得key2的值的字串:y2G |
memcached和redis同样有append的操作,但是memcached有prepend的操作,redis中并没有。
整数和浮点数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@Test public void testNumber() { jedis.flushDB(); jedis.set( "key1" , "1" ); jedis.set( "key2" , "2" ); jedis.set( "key3" , "2.3" ); System.out.println( "key1的值:" +jedis.get( "key1" )); System.out.println( "key2的值:" +jedis.get( "key2" )); System.out.println( "key1的值加1:" +jedis.incr( "key1" )); System.out.println( "获取key1的值:" +jedis.get( "key1" )); System.out.println( "key2的值减1:" +jedis.decr( "key2" )); System.out.println( "获取key2的值:" +jedis.get( "key2" )); System.out.println( "将key1的值加上整数5:" +jedis.incrBy( "key1" , 5 )); System.out.println( "获取key1的值:" +jedis.get( "key1" )); System.out.println( "将key2的值减去整数5:" +jedis.decrBy( "key2" , 5 )); System.out.println( "获取key2的值:" +jedis.get( "key2" )); } |
输出结果:
1
2
3
4
5
6
7
8
9
10
|
key1的值: 1 key2的值: 2 key1的值加 1 : 2 获取key1的值: 2 key2的值减 1 : 1 获取key2的值: 1 将key1的值加上整数 5 : 7 获取key1的值: 7 将key2的值减去整数 5 :- 4 获取key2的值:- 4 |
在redis2.6或以上版本中有这个命令:incrbyfloat,即将键存储的值加上浮点数amount,jedis-2.1.0中不支持这一操作。
列表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
@Test public void testList() { jedis.flushDB(); System.out.println( "===========添加一个list===========" ); jedis.lpush( "collections" , "ArrayList" , "Vector" , "Stack" , "HashMap" , "WeakHashMap" , "LinkedHashMap" ); jedis.lpush( "collections" , "HashSet" ); jedis.lpush( "collections" , "TreeSet" ); jedis.lpush( "collections" , "TreeMap" ); System.out.println( "collections的内容:" +jedis.lrange( "collections" , 0 , - 1 )); //-1代表倒数第一个元素,-2代表倒数第二个元素 System.out.println( "collections区间0-3的元素:" +jedis.lrange( "collections" , 0 , 3 )); System.out.println( "===============================" ); // 删除列表指定的值 ,第二个参数为删除的个数(有重复时),后add进去的值先被删,类似于出栈 System.out.println( "删除指定元素个数:" +jedis.lrem( "collections" , 2 , "HashMap" )); System.out.println( "collections的内容:" +jedis.lrange( "collections" , 0 , - 1 )); System.out.println( "删除下表0-3区间之外的元素:" +jedis.ltrim( "collections" , 0 , 3 )); System.out.println( "collections的内容:" +jedis.lrange( "collections" , 0 , - 1 )); System.out.println( "collections列表出栈(左端):" +jedis.lpop( "collections" )); System.out.println( "collections的内容:" +jedis.lrange( "collections" , 0 , - 1 )); System.out.println( "collections添加元素,从列表右端,与lpush相对应:" +jedis.rpush( "collections" , "EnumMap" )); System.out.println( "collections的内容:" +jedis.lrange( "collections" , 0 , - 1 )); System.out.println( "collections列表出栈(右端):" +jedis.rpop( "collections" )); System.out.println( "collections的内容:" +jedis.lrange( "collections" , 0 , - 1 )); System.out.println( "修改collections指定下标1的内容:" +jedis.lset( "collections" , 1 , "LinkedArrayList" )); System.out.println( "collections的内容:" +jedis.lrange( "collections" , 0 , - 1 )); System.out.println( "===============================" ); System.out.println( "collections的长度:" +jedis.llen( "collections" )); System.out.println( "获取collections下标为2的元素:" +jedis.lindex( "collections" , 2 )); System.out.println( "===============================" ); jedis.lpush( "sortedList" , "3" , "6" , "2" , "0" , "7" , "4" ); System.out.println( "sortedList排序前:" +jedis.lrange( "sortedList" , 0 , - 1 )); System.out.println(jedis.sort( "sortedList" )); System.out.println( "sortedList排序后:" +jedis.lrange( "sortedList" , 0 , - 1 )); } |
输出结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
===========添加一个list=========== collections的内容:[TreeMap, TreeSet, HashSet, LinkedHashMap, WeakHashMap, HashMap, Stack, Vector, ArrayList] collections区间 0 - 3 的元素:[TreeMap, TreeSet, HashSet, LinkedHashMap] =============================== 删除指定元素个数: 1 collections的内容:[TreeMap, TreeSet, HashSet, LinkedHashMap, WeakHashMap, Stack, Vector, ArrayList] 删除下表 0 - 3 区间之外的元素:OK collections的内容:[TreeMap, TreeSet, HashSet, LinkedHashMap] collections列表出栈(左端):TreeMap collections的内容:[TreeSet, HashSet, LinkedHashMap] collections添加元素,从列表右端,与lpush相对应: 4 collections的内容:[TreeSet, HashSet, LinkedHashMap, EnumMap] collections列表出栈(右端):EnumMap collections的内容:[TreeSet, HashSet, LinkedHashMap] 修改collections指定下标 1 的内容:OK collections的内容:[TreeSet, LinkedArrayList, LinkedHashMap] =============================== collections的长度: 3 获取collections下标为 2 的元素:LinkedHashMap =============================== sortedList排序前:[ 4 , 7 , 0 , 2 , 6 , 3 ] [ 0 , 2 , 3 , 4 , 6 , 7 ] sortedList排序后:[ 4 , 7 , 0 , 2 , 6 , 3 ] |
Redis中还有阻塞式的列表弹出命令以及在列表之间移动元素的命令:blpop, brpop, rpoplpush, brpoplpush等。
集合(Set)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
@Test public void testSet() { jedis.flushDB(); System.out.println( "============向集合中添加元素============" ); System.out.println(jedis.sadd( "eleSet" , "e1" , "e2" , "e4" , "e3" , "e0" , "e8" , "e7" , "e5" )); System.out.println(jedis.sadd( "eleSet" , "e6" )); System.out.println(jedis.sadd( "eleSet" , "e6" )); System.out.println( "eleSet的所有元素为:" +jedis.smembers( "eleSet" )); System.out.println( "删除一个元素e0:" +jedis.srem( "eleSet" , "e0" )); System.out.println( "eleSet的所有元素为:" +jedis.smembers( "eleSet" )); System.out.println( "删除两个元素e7和e6:" +jedis.srem( "eleSet" , "e7" , "e6" )); System.out.println( "eleSet的所有元素为:" +jedis.smembers( "eleSet" )); System.out.println( "随机的移除集合中的一个元素:" +jedis.spop( "eleSet" )); System.out.println( "随机的移除集合中的一个元素:" +jedis.spop( "eleSet" )); System.out.println( "eleSet的所有元素为:" +jedis.smembers( "eleSet" )); System.out.println( "eleSet中包含元素的个数:" +jedis.scard( "eleSet" )); System.out.println( "e3是否在eleSet中:" +jedis.sismember( "eleSet" , "e3" )); System.out.println( "e1是否在eleSet中:" +jedis.sismember( "eleSet" , "e1" )); System.out.println( "e1是否在eleSet中:" +jedis.sismember( "eleSet" , "e5" )); System.out.println( "=================================" ); System.out.println(jedis.sadd( "eleSet1" , "e1" , "e2" , "e4" , "e3" , "e0" , "e8" , "e7" , "e5" )); System.out.println(jedis.sadd( "eleSet2" , "e1" , "e2" , "e4" , "e3" , "e0" , "e8" )); System.out.println( "将eleSet1中删除e1并存入eleSet3中:" +jedis.smove( "eleSet1" , "eleSet3" , "e1" )); System.out.println( "将eleSet1中删除e2并存入eleSet3中:" +jedis.smove( "eleSet1" , "eleSet3" , "e2" )); System.out.println( "eleSet1中的元素:" +jedis.smembers( "eleSet1" )); System.out.println( "eleSet3中的元素:" +jedis.smembers( "eleSet3" )); System.out.println( "============集合运算=================" ); System.out.println( "eleSet1中的元素:" +jedis.smembers( "eleSet1" )); System.out.println( "eleSet2中的元素:" +jedis.smembers( "eleSet2" )); System.out.println( "eleSet1和eleSet2的交集:" +jedis.sinter( "eleSet1" , "eleSet2" )); System.out.println( "eleSet1和eleSet2的并集:" +jedis.sunion( "eleSet1" , "eleSet2" )); System.out.println( "eleSet1和eleSet2的差集:" +jedis.sdiff( "eleSet1" , "eleSet2" )); //eleSet1中有,eleSet2中没有 } |
输出结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
============向集合中添加元素============ 8 1 0 eleSet的所有元素为:[e3, e4, e1, e2, e0, e8, e7, e6, e5] 删除一个元素e0: 1 eleSet的所有元素为:[e3, e4, e1, e2, e8, e7, e6, e5] 删除两个元素e7和e6: 2 eleSet的所有元素为:[e3, e4, e1, e2, e8, e5] 随机的移除集合中的一个元素:e5 随机的移除集合中的一个元素:e2 eleSet的所有元素为:[e3, e4, e1, e8] eleSet中包含元素的个数: 4 e3是否在eleSet中: true e1是否在eleSet中: true e1是否在eleSet中: false ================================= 8 6 将eleSet1中删除e1并存入eleSet3中: 1 将eleSet1中删除e2并存入eleSet3中: 1 eleSet1中的元素:[e3, e4, e0, e8, e7, e5] eleSet3中的元素:[e1, e2] ============集合运算================= eleSet1中的元素:[e3, e4, e0, e8, e7, e5] eleSet2中的元素:[e3, e4, e1, e2, e0, e8] eleSet1和eleSet2的交集:[e3, e4, e0, e8] eleSet1和eleSet2的并集:[e3, e4, e1, e2, e0, e8, e7, e5] eleSet1和eleSet2的差集:[e7, e5] |
关于Set还有一些其他命令:srandmember, sdiffstore, sinterstore, sunionstore等。
散列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
@Test public void testHash() { jedis.flushDB(); Map<String,String> map = new HashMap<>(); map.put( "key1" , "value1" ); map.put( "key2" , "value2" ); map.put( "key3" , "value3" ); map.put( "key4" , "value4" ); jedis.hmset( "hash" ,map); jedis.hset( "hash" , "key5" , "value5" ); System.out.println( "散列hash的所有键值对为:" +jedis.hgetAll( "hash" )); //return Map<String,String> System.out.println( "散列hash的所有键为:" +jedis.hkeys( "hash" )); //return Set<String> System.out.println( "散列hash的所有值为:" +jedis.hvals( "hash" )); //return List<String> System.out.println( "将key6保存的值加上一个整数,如果key6不存在则添加key6:" +jedis.hincrBy( "hash" , "key6" , 6 )); System.out.println( "散列hash的所有键值对为:" +jedis.hgetAll( "hash" )); System.out.println( "将key6保存的值加上一个整数,如果key6不存在则添加key6:" +jedis.hincrBy( "hash" , "key6" , 3 )); System.out.println( "散列hash的所有键值对为:" +jedis.hgetAll( "hash" )); System.out.println( "删除一个或者多个键值对:" +jedis.hdel( "hash" , "key2" )); System.out.println( "散列hash的所有键值对为:" +jedis.hgetAll( "hash" )); System.out.println( "散列hash中键值对的个数:" +jedis.hlen( "hash" )); System.out.println( "判断hash中是否存在key2:" +jedis.hexists( "hash" , "key2" )); System.out.println( "判断hash中是否存在key3:" +jedis.hexists( "hash" , "key3" )); System.out.println( "获取hash中的值:" +jedis.hmget( "hash" , "key3" )); System.out.println( "获取hash中的值:" +jedis.hmget( "hash" , "key3" , "key4" )); } |
输出结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
散列hash的所有键值对为:{key4=value4, key3=value3, key5=value5, key2=value2, key1=value1} 散列hash的所有键为:[key4, key3, key5, key2, key1] 散列hash的所有值为:[value4, value3, value1, value2, value5] 将key6保存的值加上一个整数,如果key6不存在则添加key6: 6 散列hash的所有键值对为:{key4=value4, key3=value3, key6= 6 , key5=value5, key2=value2, key1=value1} 将key6保存的值加上一个整数,如果key6不存在则添加key6: 9 散列hash的所有键值对为:{key4=value4, key3=value3, key6= 9 , key5=value5, key2=value2, key1=value1} 删除一个或者多个键值对: 1 散列hash的所有键值对为:{key4=value4, key3=value3, key6= 9 , key5=value5, key1=value1} 散列hash中键值对的个数: 5 判断hash中是否存在key2: false 判断hash中是否存在key3: true 获取hash中的值:[value3] 获取hash中的值:[value3, value4] |
有序集合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
@Test public void testSortedSet() { jedis.flushDB(); Map<Double,String> map = new HashMap<>(); map.put( 1.2 , "key2" ); map.put( 4.0 , "key3" ); map.put( 5.0 , "key4" ); map.put( 0.2 , "key5" ); System.out.println(jedis.zadd( "zset" , 3 , "key1" )); System.out.println(jedis.zadd( "zset" ,map)); System.out.println( "zset中的所有元素:" +jedis.zrange( "zset" , 0 , - 1 )); System.out.println( "zset中的所有元素:" +jedis.zrangeWithScores( "zset" , 0 , - 1 )); System.out.println( "zset中的所有元素:" +jedis.zrangeByScore( "zset" , 0 , 100 )); System.out.println( "zset中的所有元素:" +jedis.zrangeByScoreWithScores( "zset" , 0 , 100 )); System.out.println( "zset中key2的分值:" +jedis.zscore( "zset" , "key2" )); System.out.println( "zset中key2的排名:" +jedis.zrank( "zset" , "key2" )); System.out.println( "删除zset中的元素key3:" +jedis.zrem( "zset" , "key3" )); System.out.println( "zset中的所有元素:" +jedis.zrange( "zset" , 0 , - 1 )); System.out.println( "zset中元素的个数:" +jedis.zcard( "zset" )); System.out.println( "zset中分值在1-4之间的元素的个数:" +jedis.zcount( "zset" , 1 , 4 )); System.out.println( "key2的分值加上5:" +jedis.zincrby( "zset" , 5 , "key2" )); System.out.println( "key3的分值加上4:" +jedis.zincrby( "zset" , 4 , "key3" )); System.out.println( "zset中的所有元素:" +jedis.zrange( "zset" , 0 , - 1 )); } |
输出结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
1 4 zset中的所有元素:[key5, key2, key1, key3, key4] zset中的所有元素:[[[ 107 , 101 , 121 , 53 ], 0.2 ], [[ 107 , 101 , 121 , 50 ], 1.2 ], [[ 107 , 101 , 121 , 49 ], 3.0 ], [[ 107 , 101 , 121 , 51 ], 4.0 ], [[ 107 , 101 , 121 , 52 ], 5.0 ]] zset中的所有元素:[key5, key2, key1, key3, key4] zset中的所有元素:[[[ 107 , 101 , 121 , 53 ], 0.2 ], [[ 107 , 101 , 121 , 50 ], 1.2 ], [[ 107 , 101 , 121 , 49 ], 3.0 ], [[ 107 , 101 , 121 , 51 ], 4.0 ], [[ 107 , 101 , 121 , 52 ], 5.0 ]] zset中key2的分值: 1.2 zset中key2的排名: 1 删除zset中的元素key3: 1 zset中的所有元素:[key5, key2, key1, key4] zset中元素的个数: 4 zset中分值在 1 - 4 之间的元素的个数: 2 key2的分值加上 5 : 6.2 key3的分值加上 4 : 4.0 zset中的所有元素:[key5, key1, key3, key4, key2] |
有序集合还有诸如zinterstore, zunionstore, zremrangebyscore, zremrangebyrank, zrevrank, zrevrange, zrangebyscore等命令。
排序sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
@Test public void testSort() { jedis.flushDB(); jedis.lpush( "collections" , "ArrayList" , "Vector" , "Stack" , "HashMap" , "WeakHashMap" , "LinkedHashMap" ); System.out.println( "collections的内容:" +jedis.lrange( "collections" , 0 , - 1 )); SortingParams sortingParameters = new SortingParams(); System.out.println(jedis.sort( "collections" ,sortingParameters.alpha())); System.out.println( "===============================" ); jedis.lpush( "sortedList" , "3" , "6" , "2" , "0" , "7" , "4" ); System.out.println( "sortedList排序前:" +jedis.lrange( "sortedList" , 0 , - 1 )); System.out.println( "升序:" +jedis.sort( "sortedList" , sortingParameters.asc())); System.out.println( "升序:" +jedis.sort( "sortedList" , sortingParameters.desc())); System.out.println( "===============================" ); jedis.lpush( "userlist" , "33" ); jedis.lpush( "userlist" , "22" ); jedis.lpush( "userlist" , "55" ); jedis.lpush( "userlist" , "11" ); jedis.hset( "user:66" , "name" , "66" ); jedis.hset( "user:55" , "name" , "55" ); jedis.hset( "user:33" , "name" , "33" ); jedis.hset( "user:22" , "name" , "79" ); jedis.hset( "user:11" , "name" , "24" ); jedis.hset( "user:11" , "add" , "beijing" ); jedis.hset( "user:22" , "add" , "shanghai" ); jedis.hset( "user:33" , "add" , "guangzhou" ); jedis.hset( "user:55" , "add" , "chongqing" ); jedis.hset( "user:66" , "add" , "xi'an" ); sortingParameters = new SortingParams(); sortingParameters.get( "user:*->name" ); sortingParameters.get( "user:*->add" ); System.out.println(jedis.sort( "userlist" ,sortingParameters)); } |
输出结果:
1
2
3
4
5
6
7
8
|
collections的内容:[LinkedHashMap, WeakHashMap, HashMap, Stack, Vector, ArrayList] [ArrayList, HashMap, LinkedHashMap, Stack, Vector, WeakHashMap] =============================== sortedList排序前:[ 4 , 7 , 0 , 2 , 6 , 3 ] 升序:[ 0 , 2 , 3 , 4 , 6 , 7 ] 升序:[ 7 , 6 , 4 , 3 , 2 , 0 ] =============================== [ 24 , beijing, 79 , shanghai, 33 , guangzhou, 55 , chongqing] |
参考资料
1. java操作redis
2. java对redis的基本操作
3. 《Redis In Action》Josiah L. Carlson
4. redis的简单使用
以下内容转自:http://blog.csdn.net/u010414666/article/details/50477064
java操作redis
这时候就可以通过Java代码操作redis了,具体代码可参考:
http://flychao88.iteye.com/blog/1527163
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import javax.sound.midi.Soundbank;
import java.util.*;
/**
* @author: flychao88
* Time: 2012.5.7 16:23:15
*/
public class RedisTest {
JedisPool pool;
Jedis jedis;
@Before
public void setUp() {
pool = new JedisPool(new JedisPoolConfig(), "172.16.100.184");
jedis = pool.getResource();
jedis.auth("password");
}
/**
* Redis存储初级的字符串
* CRUD
*/
@Test
public void testBasicString(){
//-----添加数据----------
jedis.set("name","minxr");//向key-->name中放入了value-->minxr
System.out.println(jedis.get("name"));//执行结果:minxr
//-----修改数据-----------
//1、在原来基础上修改
jedis.append("name","jarorwar"); //很直观,类似map 将jarorwar append到已经有的value之后
System.out.println(jedis.get("name"));//执行结果:minxrjarorwar
//2、直接覆盖原来的数据
jedis.set("name","闵晓荣");
System.out.println(jedis.get("name"));//执行结果:闵晓荣
//删除key对应的记录
jedis.del("name");
System.out.println(jedis.get("name"));//执行结果:null
/**
* mset相当于
* jedis.set("name","minxr");
* jedis.set("jarorwar","闵晓荣");
*/
jedis.mset("name","minxr","jarorwar","闵晓荣");
System.out.println(jedis.mget("name","jarorwar"));
}
/**
* jedis操作Map
*/
@Test
public void testMap(){
Map<String,String> user=new HashMap<String,String>();
user.put("name","minxr");
user.put("pwd","password");
jedis.hmset("user",user);
//取出user中的name,执行结果:[minxr]-->注意结果是一个泛型的List
//第一个参数是存入redis中map对象的key,后面跟的是放入map中的对象的key,后面的key可以跟多个,是可变参数
List<String> rsmap = jedis.hmget("user", "name");
System.out.println(rsmap);
//删除map中的某个键值
// jedis.hdel("user","pwd");
System.out.println(jedis.hmget("user", "pwd")); //因为删除了,所以返回的是null
System.out.println(jedis.hlen("user")); //返回key为user的键中存放的值的个数1
System.out.println(jedis.exists("user"));//是否存在key为user的记录 返回true
System.out.println(jedis.hkeys("user"));//返回map对象中的所有key [pwd, name]
System.out.println(jedis.hvals("user"));//返回map对象中的所有value [minxr, password]
Iterator<String> iter=jedis.hkeys("user").iterator();
while (iter.hasNext()){
String key = iter.next();
System.out.println(key+":"+jedis.hmget("user",key));
}
}
/**
* jedis操作List
*/
@Test
public void testList(){
//开始前,先移除所有的内容
jedis.del("java framework");
System.out.println(jedis.lrange("java framework",0,-1));
//先向key java framework中存放三条数据
jedis.lpush("java framework","spring");
jedis.lpush("java framework","struts");
jedis.lpush("java framework","hibernate");
//再取出所有数据jedis.lrange是按范围取出,
// 第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有
System.out.println(jedis.lrange("java framework",0,-1));
}
/**
* jedis操作Set
*/
@Test
public void testSet(){
//添加
jedis.sadd("sname","minxr");
jedis.sadd("sname","jarorwar");
jedis.sadd("sname","闵晓荣");
jedis.sadd("sanme","noname");
//移除noname
jedis.srem("sname","noname");
System.out.println(jedis.smembers("sname"));//获取所有加入的value
System.out.println(jedis.sismember("sname", "minxr"));//判断 minxr 是否是sname集合的元素
System.out.println(jedis.srandmember("sname"));
System.out.println(jedis.scard("sname"));//返回集合的元素个数
}
@Test
public void test() throws InterruptedException {
//keys中传入的可以用通配符
System.out.println(jedis.keys("*")); //返回当前库中所有的key [sose, sanme, name, jarorwar, foo, sname, java framework, user, braand]
System.out.println(jedis.keys("*name"));//返回的sname [sname, name]
System.out.println(jedis.del("sanmdde"));//删除key为sanmdde的对象 删除成功返回1 删除失败(或者不存在)返回 0
System.out.println(jedis.ttl("sname"));//返回给定key的有效时间,如果是-1则表示永远有效
jedis.setex("timekey", 10, "min");//通过此方法,可以指定key的存活(有效时间) 时间为秒
Thread.sleep(5000);//睡眠5秒后,剩余时间将为<=5
System.out.println(jedis.ttl("timekey")); //输出结果为5
jedis.setex("timekey", 1, "min"); //设为1后,下面再看剩余时间就是1了
System.out.println(jedis.ttl("timekey")); //输出结果为1
System.out.println(jedis.exists("key"));//检查key是否存在
System.out.println(jedis.rename("timekey","time"));
System.out.println(jedis.get("timekey"));//因为移除,返回为null
System.out.println(jedis.get("time")); //因为将timekey 重命名为time 所以可以取得值 min
//jedis 排序
//注意,此处的rpush和lpush是List的操作。是一个双向链表(但从表现来看的)
jedis.del("a");//先清除数据,再加入数据进行测试
jedis.rpush("a", "1");
jedis.lpush("a","6");
jedis.lpush("a","3");
jedis.lpush("a","9");
System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1]
System.out.println(jedis.sort("a")); //[1, 3, 6, 9] //输入排序后结果
System.out.println(jedis.lrange("a",0,-1));
}
这边博客中的jar可以自行百度下载,如果会用maven那更好不过,简单配置一下即可。
如果运行代码时,在pool那获取resource报错,请常识关闭linux的防火墙,(centos下)执行如下命令:
sudo service iptables stop
关闭防火墙需要root权限,所以命令加上sudo前缀,如果是root用户登录不需要这个sudo
redis默认未开启用户认证,如果运行上面博文的代码时写了下面代码会报错
jedis.auth("password");
需在redis中开启认证,或将这一句注释掉即可,待redis配置和使用熟悉后再设置验证相关配置。
以下内容转自:http://www.cnblogs.com/liuling/p/2014-4-19-04.html
使用Java操作Redis需要jedis-2.1.0.jar,下载地址:https://files.cnblogs.com/liuling/jedis-2.1.0.jar.zip
如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar,下载地址:https://files.cnblogs.com/liuling/commons-pool-1.5.4.jar.zip
1 package com.test; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.List; 6 import java.util.Map; 7 8 import org.junit.Before; 9 import org.junit.Test; 10 11 import redis.clients.jedis.Jedis; 12 13 public class TestRedis { 14 private Jedis jedis; 15 16 @Before 17 public void setup() { 18 //连接redis服务器,192.168.0.100:6379 19 jedis = new Jedis("192.168.0.100", 6379); 20 //权限认证 21 jedis.auth("admin"); 22 } 23 24 /** 25 * redis存储字符串 26 */ 27 @Test 28 public void testString() { 29 //-----添加数据---------- 30 jedis.set("name","xinxin");//向key-->name中放入了value-->xinxin 31 System.out.println(jedis.get("name"));//执行结果:xinxin 32 33 jedis.append("name", " is my lover"); //拼接 34 System.out.println(jedis.get("name")); 35 36 jedis.del("name"); //删除某个键 37 System.out.println(jedis.get("name")); 38 //设置多个键值对 39 jedis.mset("name","liuling","age","23","qq","476777XXX"); 40 jedis.incr("age"); //进行加1操作 41 System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq")); 42 43 } 44 45 /** 46 * redis操作Map 47 */ 48 @Test 49 public void testMap() { 50 //-----添加数据---------- 51 Map<String, String> map = new HashMap<String, String>(); 52 map.put("name", "xinxin"); 53 map.put("age", "22"); 54 map.put("qq", "123456"); 55 jedis.hmset("user",map); 56 //取出user中的name,执行结果:[minxr]-->注意结果是一个泛型的List 57 //第一个参数是存入redis中map对象的key,后面跟的是放入map中的对象的key,后面的key可以跟多个,是可变参数 58 List<String> rsmap = jedis.hmget("user", "name", "age", "qq"); 59 System.out.println(rsmap); 60 61 //删除map中的某个键值 62 jedis.hdel("user","age"); 63 System.out.println(jedis.hmget("user", "age")); //因为删除了,所以返回的是null 64 System.out.println(jedis.hlen("user")); //返回key为user的键中存放的值的个数2 65 System.out.println(jedis.exists("user"));//是否存在key为user的记录 返回true 66 System.out.println(jedis.hkeys("user"));//返回map对象中的所有key 67 System.out.println(jedis.hvals("user"));//返回map对象中的所有value 68 69 Iterator<String> iter=jedis.hkeys("user").iterator(); 70 while (iter.hasNext()){ 71 String key = iter.next(); 72 System.out.println(key+":"+jedis.hmget("user",key)); 73 } 74 } 75 76 /** 77 * jedis操作List 78 */ 79 @Test 80 public void testList(){ 81 //开始前,先移除所有的内容 82 jedis.del("java framework"); 83 System.out.println(jedis.lrange("java framework",0,-1)); 84 //先向key java framework中存放三条数据 85 jedis.lpush("java framework","spring"); 86 jedis.lpush("java framework","struts"); 87 jedis.lpush("java framework","hibernate"); 88 //再取出所有数据jedis.lrange是按范围取出, 89 // 第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有 90 System.out.println(jedis.lrange("java framework",0,-1)); 91 92 jedis.del("java framework"); 93 jedis.rpush("java framework","spring"); 94 jedis.rpush("java framework","struts"); 95 jedis.rpush("java framework","hibernate"); 96 System.out.println(jedis.lrange("java framework",0,-1)); 97 } 98 99 /** 100 * jedis操作Set 101 */ 102 @Test 103 public void testSet(){ 104 //添加 105 jedis.sadd("user","liuling"); 106 jedis.sadd("user","xinxin"); 107 jedis.sadd("user","ling"); 108 jedis.sadd("user","zhangxinxin"); 109 jedis.sadd("user","who"); 110 //移除noname 111 jedis.srem("user","who"); 112 System.out.println(jedis.smembers("user"));//获取所有加入的value 113 System.out.println(jedis.sismember("user", "who"));//判断 who 是否是user集合的元素 114 System.out.println(jedis.srandmember("user")); 115 System.out.println(jedis.scard("user"));//返回集合的元素个数 116 } 117 118 @Test 119 public void test() throws InterruptedException { 120 //jedis 排序 121 //注意,此处的rpush和lpush是List的操作。是一个双向链表(但从表现来看的) 122 jedis.del("a");//先清除数据,再加入数据进行测试 123 jedis.rpush("a", "1"); 124 jedis.lpush("a","6"); 125 jedis.lpush("a","3"); 126 jedis.lpush("a","9"); 127 System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1] 128 System.out.println(jedis.sort("a")); //[1, 3, 6, 9] //输入排序后结果 129 System.out.println(jedis.lrange("a",0,-1)); 130 } 131 132 @Test 133 public void testRedisPool() { 134 RedisUtil.getJedis().set("newname", "中文测试"); 135 System.out.println(RedisUtil.getJedis().get("newname")); 136 } 137 }
Redis连接池:
1 package com.test; 2 3 import redis.clients.jedis.Jedis; 4 import redis.clients.jedis.JedisPool; 5 import redis.clients.jedis.JedisPoolConfig; 6 7 public final class RedisUtil { 8 9 //Redis服务器IP 10 private static String ADDR = "192.168.0.100"; 11 12 //Redis的端口号 13 private static int PORT = 6379; 14 15 //访问密码 16 private static String AUTH = "admin"; 17 18 //可用连接实例的最大数目,默认值为8; 19 //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。 20 private static int MAX_ACTIVE = 1024; 21 22 //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。 23 private static int MAX_IDLE = 200; 24 25 //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException; 26 private static int MAX_WAIT = 10000; 27 28 private static int TIMEOUT = 10000; 29 30 //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的; 31 private static boolean TEST_ON_BORROW = true; 32 33 private static JedisPool jedisPool = null; 34 35 /** 36 * 初始化Redis连接池 37 */ 38 static { 39 try { 40 JedisPoolConfig config = new JedisPoolConfig(); 41 config.setMaxActive(MAX_ACTIVE); 42 config.setMaxIdle(MAX_IDLE); 43 config.setMaxWait(MAX_WAIT); 44 config.setTestOnBorrow(TEST_ON_BORROW); 45 jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 } 50 51 /** 52 * 获取Jedis实例 53 * @return 54 */ 55 public synchronized static Jedis getJedis() { 56 try { 57 if (jedisPool != null) { 58 Jedis resource = jedisPool.getResource(); 59 return resource; 60 } else { 61 return null; 62 } 63 } catch (Exception e) { 64 e.printStackTrace(); 65 return null; 66 } 67 } 68 69 /** 70 * 释放jedis资源 71 * @param jedis 72 */ 73 public static void returnResource(final Jedis jedis) { 74 if (jedis != null) { 75 jedisPool.returnResource(jedis); 76 } 77 } 78 }