1. Demo - 总
public class RedisMain {
public static void main(String[] args) throws InterruptedException {
Jedis jedis = JedisUtil.getJedis();
jedis.auth("123456Aa");
testList(jedis);
System.out.println("=======================");
testSet(jedis);
System.out.println("=======================");
testZset(jedis);
Set<String> keys = jedis.keys("*");
if (keys != null) {
keys.forEach(jedis::del);
}
jedis.close();
}
}
2. String
private static void testString(Jedis jedis) throws InterruptedException {
jedis.set("username", "test");
jedis.setex("username-expire", 2, "test-expire");
String username = jedis.get("username");
String usernameExpire = jedis.get("username-expire");
System.out.println(username);
System.out.println(usernameExpire);
Thread.sleep(3000);
username = jedis.get("username");
usernameExpire = jedis.get("username-expire");
System.out.println(username);
System.out.println(usernameExpire);
jedis.del("username");
username = jedis.get("username");
System.out.println(username);
}
3. Hash
private static void testHash(Jedis jedis) {
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
jedis.hset("mymap", map);
System.out.println(jedis.hget("mymap", "key1"));
System.out.println(jedis.hgetAll("mymap"));
jedis.hdel("mymap", "key1");
System.out.println(jedis.hgetAll("mymap"));
}
4. List
public static void testList(Jedis jedis) {
jedis.lpush("mylist", "first-left", "second-left");
jedis.rpush("mylist", "first-right", "second-right");
System.out.println(jedis.lrange("mylist", 0, -1));
System.out.println(jedis.lpop("mylist"));
System.out.println(jedis.rpop("mylist"));
System.out.println(jedis.lrange("mylist", 0, -1));
}
5. Set
private static void testSet(Jedis jedis) {
jedis.sadd("myset", "a", "b", "c");
System.out.println(jedis.smembers("myset"));
jedis.srem("myset", "c");
System.out.println(jedis.smembers("myset"));
}
6. Zset
private static void testZset(Jedis jedis) {
jedis.zadd("my-sort-set", 99, "c");
jedis.zadd("my-sort-set", 97, "a");
jedis.zadd("my-sort-set", 98, "b");
System.out.println(jedis.zrange("my-sort-set", 0, -1));
jedis.zrem("my-sort-set", "a");
System.out.println(jedis.zrange("my-sort-set", 0, -1));
}
7. Jedis连接池
public class JedisUtil {
private static final JedisPool jedisPool;
static {
InputStream is = JedisUtil.class.getClassLoader().getResourceAsStream("redis/redis.properties");
Properties pro = new Properties();
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
jedisPool = new JedisPool(config, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));
}
public static Jedis getJedis() {
return jedisPool.getResource();
}
}