Jedis简介,Jedis 的 HelloWorld,设置redis连接密码,Jedis 连接池实例,和jedis常用方法

Jedis简介

实际开发中,我们需要用Redis的连接工具连接Redis然后操作Redis。

redis都提供了对应的客户端  https://redis.io/clients

官方推荐的是Jedis  托管地址:https://github.com/xetorthio/jedis

那jedis就是集成了redis的一些命令操作,封装了redis的java客户端。提供了连接池管理。一般不直接使用jedis,而是在其上在封装一层,作为业务的使用。如果用spring的话,可以看看spring 封装的 redis Spring Data Redis

Jedis连接 HelloWorld实现

pom里加下jedis依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
    @Test
    public void jedisSingle(){
        Jedis jedis = new Jedis("xxxx", 6379);
        jedis.auth("root");
        jedis.set("jedis", "hello word");
        String name = jedis.get("jedis");
        System.out.println(name);
        jedis.close();
    }

运行 报错了   连接超时.

我们配置下防火墙 开一个6379端口权限

继续运行 还是报错 连接超时 错误;

我们配置下 redis配置文件 redis.conf

这里绑定了本机,我们把这个备注掉; # bind 127.0.0.1

配置完后 

[root@localhost redis]# ./bin/redis-cli shutdown

[root@localhost redis]# ./bin/redis-server ./redis.conf

要重启下redis服务;

继续运行 又报错了

Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.

at redis.clients.jedis.Protocol.processError(Protocol.java:127)

at redis.clients.jedis.Protocol.process(Protocol.java:161)

at redis.clients.jedis.Protocol.read(Protocol.java:215)

at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:340)

at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:239)

at redis.clients.jedis.Jedis.set(Jedis.java:121)

at com.java1234.redis.JedisTest.main(JedisTest.java:14)

有两种方法 解决

 

第一种 直接去掉自我保护功能(不推荐)

[root@localhost redis]# vi /usr/local/redis/redis.conf

进入配置      找到 protected-mode yes     改成 no即可      编辑后 重启redis服务,然后运行 ,结果出来了

第二种 设置redis连接密码

进入客户端

[root@localhost redis]# ./bin/redis-cli

127.0.0.1:6379> config set requirepass 123456

设置密码 123456

127.0.0.1:6379> quit

[root@localhost redis]# ./bin/redis-cli

127.0.0.1:6379> auth 123456

OK

说明设置成功
这样就OK了

 

Jedis 连接池实例

    @Test
    public void jedisPool(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(30);//最大连接数
        config.setMaxIdle(10);//最大空闲连接数
        try (JedisPool jedisPool = new JedisPool(config, "xxxxx", 6379); Jedis jedis = jedisPool.getResource()) {
            jedis.auth("root");
            jedis.set("jedis", "谢飞");
            String name = jedis.get("jedis");
            System.out.println(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

常用用法:

Jedis jedis;
 
@Before
public void connectionTest() {
jedis = new Jedis("127.0.0.1", 6379);//redis的地址以及连接端口
//jedis.auth("helloworld");  //开启密码验证(配置文件中为 requirepass helloworld)的时候需要执行该方法
}

Jedis对key的操作

@Test
public void keyTest() throws UnsupportedEncodingException {
System.out.println(jedis.flushDB());// 清空数据
System.out.println(jedis.echo("hello"));
 
// 判断key否存在
System.out.println(jedis.exists("foo"));
 
jedis.set("key", "values");
jedis.set("key2", "values");
System.out.println(jedis.exists("key"));// 判断是否存在
 
// 如果数据库没有任何key,返回nil,否则返回数据库中一个随机的key。
String randomKey = jedis.randomKey();
System.out.println("randomKey: " + randomKey);
 
// 设置60秒后该key过期
jedis.expire("key", 60);
 
// key有效毫秒数
System.out.println(jedis.pttl("key"));
 
// 移除key的过期时间
jedis.persist("key");
 
// 获取key的类型, "string", "list", "set". "none" none表示key不存在
System.out.println("type: " + jedis.type("key"));
 
// 导出key的值
byte[] bytes = jedis.dump("key");
System.out.println(new String(bytes));
 
// 将key重命名
jedis.renamenx("key", "keytest");
System.out.println("key是否存在: " + jedis.exists("key"));// 判断是否存在
System.out.println("keytest是否存在: " + jedis.exists("keytest"));// 判断是否存在
 
// 查询匹配的key
// KEYS       * 匹配数据库中所有 key 。
// KEYS       h?llo 匹配 hello , hallo 和 hxllo 等。
// KEYS       h*llo 匹配 hllo 和 heeeeello 等。
// KEYS       h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo 。
// 特殊符号用 \ 隔开。
Set<String> set = jedis.keys("k*");
System.out.println(set);
 
// 删除key
jedis.del("key");
System.out.println(jedis.exists("key"));
}

Jedis对字符串(String)的相关操作

@Test
public void stringTest() {
jedis.set("hello", "hello");
System.out.println(jedis.get("hello"));
 
// 使用append 向字符串后面添加
jedis.append("hello", " world");
System.out.println(jedis.get("hello"));
 
// set覆盖字符串
jedis.set("hello", "123");
System.out.println(jedis.get("hello"));
 
// 设置过期时间
jedis.setex("hello2", 2, "world2");
System.out.println(jedis.get("hello2"));
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
System.out.println(jedis.get("hello2"));
 
// 一次添加多个key-value对
jedis.mset("a", "1", "b", "2");
// 获取a和b的value
List<String> valus = jedis.mget("a", "b");
System.out.println(valus);
 
// 批量删除
jedis.del("a", "b");
System.out.println(jedis.exists("a"));
System.out.println(jedis.exists("b"));
}

Jedis对链表(Lists)的操作

@Test
public void listTest() {
String key = "mylist";
jedis.del(key);
 
// 队列添加元素
jedis.rpush(key, "aaaa");
jedis.rpush(key, "aaaa");
jedis.rpush(key, "bbbb");
jedis.rpush(key, "cccc");
jedis.rpush(key, "cccc");
 
// 队列长度
System.out.println("lenth: " + jedis.llen(key));
 
// 打印队列,从索引0开始,到倒数第1个(全部元素)
System.out.println("all elements: " + jedis.lrange(key, 0, -1));
 
// 索引为1的元素
System.out.println("index of 1: " + jedis.lindex(key, 1));
 
// 设置队列里面一个元素的值,当index超出范围时会返回一个error。
jedis.lset(key, 1, "aa22");
System.out.println("index of 1: " + jedis.lindex(key, 1));
 
// 从队列的右边入队一个元素
jedis.rpush(key, "-2", "-1");// 先-2,后-1入队列
System.out.println("all elements: " + jedis.lrange(key, 0, -1));
 
// 从队列的左边入队一个或多个元素
jedis.lpush(key, "second element", "first element");// 先second
// element,后first
// elementF入队列
System.out.println("all elements: " + jedis.lrange(key, 0, -1));
 
// 从队列的右边出队一个元素
System.out.println(jedis.rpop(key));
// 从队列的左边出队一个元素
System.out.println(jedis.lpop(key));
System.out.println("all elements: " + jedis.lrange(key, 0, -1));
 
// count > 0: 从头往尾移除值为 value 的元素,count为移除的个数。
// count < 0: 从尾往头移除值为 value 的元素,count为移除的个数。
// count = 0: 移除所有值为 value 的元素。
jedis.lrem(key, 1, "cccc");
System.out.println("all elements: " + jedis.lrange(key, 0, -1));
 
// 即最右边的那个元素也会被包含在内。 如果start比list的尾部下标大的时候,会返回一个空列表。
// 如果stop比list的实际尾部大的时候,Redis会当它是最后一个元素的下标。
System.out.println(jedis.lrange(key, 0, 2));
System.out.println("all elements: " + jedis.lrange(key, 0, -1));
 
// 删除区间以外的元素
System.out.println(jedis.ltrim(key, 0, 2));
System.out.println("all elements: " + jedis.lrange(key, 0, -1));
}

Jedis对集合(Sets)的操作

@Test
public void testSet() {
// 清空数据
System.out.println(jedis.flushDB());
String key = "myset";
String key2 = "myset2";
 
// 集合添加元素
jedis.sadd(key, "aaa", "bbb", "ccc");
jedis.sadd(key2, "bbb", "ccc", "ddd");
 
// 获取集合里面的元素数量
System.out.println(jedis.scard(key));
 
// 获得两个集合的交集,并存储在一个关键的结果集
jedis.sinterstore("destination", key, key2);
System.out.println(jedis.smembers("destination"));
 
// 获得两个集合的并集,并存储在一个关键的结果集
jedis.sunionstore("destination", key, key2);
System.out.println(jedis.smembers("destination"));
 
// key集合中,key2集合没有的元素,并存储在一个关键的结果集
jedis.sdiffstore("destination", key, key2);
System.out.println(jedis.smembers("destination"));
 
// 确定某个元素是一个集合的成员
System.out.println(jedis.sismember(key, "aaa"));
 
// 从key集合里面随机获取一个元素
System.out.println(jedis.srandmember(key));
 
// aaa从key移动到key2集合
jedis.smove(key, key2, "aaa");
System.out.println(jedis.smembers(key));
System.out.println(jedis.smembers(key2));
 
// 删除并获取一个集合里面的元素
System.out.println(jedis.spop(key));
 
// 从集合里删除一个或多个元素
jedis.srem(key2, "ccc", "ddd");
System.out.println(jedis.smembers(key2));
}

Jedis对有序集合(Sorted Sets)的操作

@Test
public void testSortSet() {
// 清空数据
System.out.println(jedis.flushDB());
String key = "mysortset";
 
Map<String, Double> scoreMembers = new HashMap<String, Double>();
scoreMembers.put("aaa", 1001.0);
scoreMembers.put("bbb", 1002.0);
scoreMembers.put("ccc", 1003.0);
 
// 添加数据
jedis.zadd(key, 1004.0, "ddd");
jedis.zadd(key, scoreMembers);
 
// 获取一个排序的集合中的成员数量
System.out.println(jedis.zcard(key));
 
// 返回的成员在指定范围内的有序集合,以0表示有序集第一个成员,以1表示有序集第二个成员,以此类推。
// 负数下标,以-1表示最后一个成员,-2表示倒数第二个成员
Set<String> coll = jedis.zrange(key, 0, -1);
System.out.println(coll);
 
// 返回的成员在指定范围内的逆序集合
coll = jedis.zrevrange(key, 0, -1);
System.out.println(coll);
 
// 元素下标
System.out.println(jedis.zscore(key, "bbb"));
 
// 删除元素
System.out.println(jedis.zrem(key, "aaa"));
System.out.println(jedis.zrange(key, 0, -1));
 
// 给定值范围内的成员数
System.out.println(jedis.zcount(key, 1002.0, 1003.0));
}

Jedis对哈希(Hashs)的操作

@Test
public void testHash() {
// 清空数据
System.out.println(jedis.flushDB());
String key = "myhash";
Map<String, String> hash = new HashMap<String, String>();
hash.put("aaa", "11");
hash.put("bbb", "22");
hash.put("ccc", "33");
 
// 添加数据
jedis.hmset(key, hash);
jedis.hset(key, "ddd", "44");
 
// 获取hash的所有元素(key值)
System.out.println(jedis.hkeys(key));
 
// 获取hash中所有的key对应的value值
System.out.println(jedis.hvals(key));
 
// 获取hash里所有元素的数量
System.out.println(jedis.hlen(key));
 
// 获取hash中全部的域和值,以Map<String, String> 的形式返回
Map<String, String> elements = jedis.hgetAll(key);
System.out.println(elements);
 
// 判断给定key值是否存在于哈希集中
System.out.println(jedis.hexists(key, "bbb"));
 
// 获取hash里面指定字段对应的值
System.out.println(jedis.hmget(key, "aaa", "bbb"));
 
// 获取指定的值
System.out.println(jedis.hget(key, "aaa"));
 
// 删除指定的值
System.out.println(jedis.hdel(key, "aaa"));
System.out.println(jedis.hgetAll(key));
 
// 为key中的域 field 的值加上增量 increment
System.out.println(jedis.hincrBy(key, "bbb", 100));
System.out.println(jedis.hgetAll(key));
}

Jedis操作事务

@Test
public void testTransaction() {
Transaction t = jedis.multi();
t.set("hello", "world");
Response<String> response = t.get("hello");
 
t.zadd("foo", 1, "barowitch");
t.zadd("foo", 0, "barinsky");
t.zadd("foo", 0, "barikoviev");
Response<Set<String>> sose = t.zrange("foo", 0, -1); //  返回全部相应并以有序集合的方式返回
System.out.println(response);
System.out.println(sose);
t.exec(); // 此行注意,不能缺少
 
String foolbar = response.get(); // Response.get() 可以从响应中获取数据
 
int soseSize = sose.get().size(); // sose.get() 会立即调用set方法
System.out.println(foolbar);
System.out.println(sose.get());
}

Jedis操作管道

@Test
    public void testTransactionPipeling() {
        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);
        System.out.println(pipeString);
        System.out.println(sose);
 
        p.sync();//提交
 
        System.out.println("==========");
        System.out.println(p.get("fool"));
        System.out.println(p.zrange("foo", 0, -1));
 
        int soseSize = sose.get().size();
        Set<String> setBack = sose.get();
 
        System.out.println(soseSize);
        System.out.println(setBack);
    }

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值