Redis具体实现功能
具体实现功能
import cn.itcast.util.JedisPoolUtils;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ReadTest {
Test1
public void test1() {
//1.获取连接
Jedis jedis =new Jedis("localhost",6379);
//2.操作
jedis.set("username","zhangsan");
//3.关闭连接
jedis.close();
}
@Test2
public void test2(){
//1.获取连接
Jedis jedis =new Jedis();
//2.操作
//存储
String username = jedis.get("username");
System.out.println(username);
//可以使用setex()方法存储可以指定过期的时间,key value
jedis.setex("activecode",20,"here");
//将activecode(随便起): here键值对存入redis,并且20秒后自动删除该键值对
jedis.set("username","zhangsan");
//3.关闭连接
jedis.close();
}
@Test3
public void test3(){
//1.获取连接
Jedis jedis =new Jedis();
//2.操作
//存储hash
jedis.hset("user","name","lisi");
jedis.hset("user","age","23");
jedis.hset("user","gender","male");
//获取
String name = jedis.hget("user", "name");
System.out.println(name);
//获取hash所有map
Map<String, String> user = jedis.hgetAll("user");
Set<String> keySet = user.keySet();
for (String key:keySet){
//获取value
String value = user.get(key);
System.out.println("key: "+key+" value "+value);
}
//3.关闭连接
jedis.close();
}
@Test4
public void Test4(){
//1.获取连接
Jedis jedis =new Jedis();
//2.操作
//存储list
jedis.lpush("mylist","a","b","c");
jedis.rpush("mylist","a","b","c");
List<String> mylist = jedis.lrange("mylist", 0, -1);
System.out.println(mylist);
String e = jedis.lpop("mylist");
//3.关闭连接
jedis.close();
}
@Test5
public void Test5(){
//1.获取连接
Jedis jedis =new Jedis();
//2.操作
//存储set
jedis.sadd("myset","java","php","c++");
Set<String> myset = jedis.smembers("myset");
System.out.println(myset);
//3.关闭连接
jedis.close();
}
@Test6
public void Test6(){
//1.获取连接
Jedis jedis =new Jedis();
//2.操作
//存储sortset
jedis.zadd("mysort",3,"亚瑟");
jedis.zadd("mysort",6,"后裔");
Set<String> mysort = jedis.zrange("mysort", 0, -1);
System.out.println(mysort);
//3.关闭连接
jedis.close();
}
/**
* jedis连接池使用
*/
@Test7
public void test7(){
//0.创建一个配置对象
JedisPoolConfig config =new JedisPoolConfig();
config.setMaxTotal(50);//配置最大访问量
config.setMaxIdle(10);//配置最大空闲量
//1.创建jedis连接池对象
JedisPool jedisPool = new JedisPool();
//2.获取连接
Jedis jedis = jedisPool.getResource();
//3.使用
jedis.set("hehe","haha");
//4.关闭,归还到连接池中
jedis.close();
}
/**
* jedis连接池工具类使用
*/
@Test
public void test8(){
//通过连接池工具类获取
Jedis jedis = JedisPoolUtils.getJedis();
//3.使用
jedis.set("hello","world");
//4.关闭,归还到连接池中
jedis.close();
}
}