SpringBoot整合Jedis操作redis

1.1. Jedis所需要的jar包

redis.clients
jedis
3.2.0

1.1. 连接Redis注意事项
禁用Linux的防火墙:Linux(CentOS7)里执行命令
systemctl stop/disable firewalld.service
redis.conf中注释掉bind 127.0.0.1 ,然后 protected-mode no

1.2. Jedis常用操作
1.2.1. 创建动态的工程

1.2.1. 创建测试程序

public static void main(String[] args) {
    //创建Jedis对象
    Jedis jedis = new Jedis("192.168.60.10", 6379);
    //测试
    String ping = jedis.ping();
    System.out.println(ping);
    jedis.close();
}

1.3. 测试相关数据类型(其实使用Jedis和使用redis操操作没什么区别)
1.3.1. Jedis-API: Key

//操作key String
@Test
public void demo1() {
    //创建Jedis对象
    Jedis jedis = new Jedis("192.168.60.10", 6379);
    //添加
    jedis.set("name", "luck");
    String name = jedis.get("name");
    System.out.println(name);
    //设置多个key-value
    jedis.mset("k1", "v1", "k2", "v2");
    List<String> mget = jedis.mget("k1", "k2");
    System.out.println(mget);


    Set<String> keys = jedis.keys("*");
    for (String key : keys
    ) {
        System.out.println(key);
    }
    jedis.close();

}

1.3.2. Jedis-API: String
jedis.mset(“str1”,“v1”,“str2”,“v2”,“str3”,“v3”);
System.out.println(jedis.mget(“str1”,“str2”,“str3”));

1.3.3. Jedis-API: List
/**
* 操作list
*/
@Test
public void demo2() {
Jedis jedis = new Jedis(“192.168.60.10”, 6379);
jedis.lpush(“key1”, “lucy”, “marry”, “jack”);
//0 ,-1表示全部都取出来
List key1 = jedis.lrange(“key1”, 0, -1);
System.out.println(key1);
jedis.close();

}

1.3.4. Jedis-API: set

/**
 * set
 */
@Test
public void demo3() {
    Jedis jedis = null;
    try {
        jedis = new Jedis("192.168.60.10", 6379);
        jedis.sadd("names", "lucy", "jack");
        Set<String> smembers = jedis.smembers("names");
        for (String name : smembers) {
            System.out.println(name);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        jedis.close();
    }


}

1.3.5. Jedis-API: hash
/**
* hash操练
*/
@Test
public void demo4() {
Jedis jedis = new Jedis(“192.168.60.10”, 6379);
jedis.hset(“users”, “age”, “20”);
System.out.println(jedis.hget(“users”, “age”));
Map<String, String> map = new HashMap<String, String> ();
map.put(“telephone”, “12346513746874”);
map.put(“email”, “158@163.com”);
jedis.hmset(“hash2”, map);
List hash2 = jedis.hmget(“hash2”, “telephone”, “email”);
System.out.println(hash2);
jedis.close();

}

1.3.6. Jedis-API: zset
/**
* 操作zset
*
*/
@Test
public void demo5() {
Jedis jedis = new Jedis(“192.168.60.10”, 6379);
jedis.zadd(“china”, 100, “shanghai”);
jedis.zadd(“china”, 200, “beijing”);
jedis.zadd(“china”, 300, “shengzhen”);
jedis.zadd(“china”, 400, “guangzhou”);
Set china = jedis.zrange(“china”, 0, -1);
System.out.println(china);
jedis.close();

}
上一篇:Delphi中inherited问题


下一篇:Jedis工具类