Redis(Remote Dictionary Server,远程数据字典服务器)是一个开源的高性能内存数据库,常用作缓存缓存服务器使用,也已做消息队列使用。因其高性能、丰富的数据类型、可扩展等特性受开发者青睐,这里介绍在java中使用Jedis操作Redis的基本用法。
1. 字符串String。package com.zws.redis.examples;
import java.util.concurrent.TimeUnit;
import redis.clients.jedis.Jedis;
public class RedisString {
public static void main(String[] args) throws InterruptedException {
String host = "192.168.137.131";
int port = 6379;
String password = "redis";
Jedis jedis = new Jedis(host, port);
jedis.auth(password);
jedis.ping();
jedis.set("name", "张三");//设置
jedis.set("age", "23");
String name = jedis.get("name");//获取
String age = jedis.get("age");
System.out.println("name:" + name + ",age:" + age);
jedis.set("name", "李四");//覆盖
name = jedis.get("name");
System.out.println("name:" + name);
jedis.append("name", "-尼古拉斯");//追加
name = jedis.get("name");//获取
age = jedis.get("age");
System.out.println("name:" + name + ",age:" + age);
jedis.del("name");//删除
name = jedis.get("name");
System.out.println("name:" + name);
jedis.del("name", "age");//删除多个key
name = jedis.get("name");//获取
age = jedis.get("age");
System.out.println("name:" + name + ",age:" + age);
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("key1:" + jedis.get("key1"));
System.out.println("key2:" + 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("key3:" + 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("key2:" + jedis.get("key2"));
System.out.println("截取key2的值:" + jedis.getrange("key2", 2, 4));
jedis.close();
}
}
2. 集合List。package com.zws.redis.examples;
import java.util.List;
import redis.clients.jedis.Jedis;
public class RedisList {
public static void main(String[] args) {
String host = "192.168.137.131";
int port = 6379;
Jedis jedis = new Jedis(host, port);
jedis.auth("redis");
jedis.ping();
System.out.println("===========添加一个list===========");
Long cnt = jedis.del("collections");
System.out.println("del cnt:" + cnt);
jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
jedis.lpush("collections", "HashSet");
jedis.lpush("collections", "TreeSet");
jedis.lpush("collections", "TreeMap");
jedi

本文详细介绍了在Java中使用Jedis库操作Redis的各种基本操作,包括字符串、集合、散列、集合、排序集和键的相关操作。通过示例代码展示了如何设置、获取、删除键值对,以及如何进行列表、集合的添加、删除和排序等操作。
最低0.47元/天 解锁文章

786

被折叠的 条评论
为什么被折叠?



