zoukankan      html  css  js  c++  java
  • Jedis

    Jedis

    Java语言操作Redis的中间件

    Java代码

    添加依赖

        <dependencies>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.28</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>3.2.0</version>
            </dependency>
        </dependencies>

    测试Ping命令

    public class TestJedis {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.223.129",6379);
    //如果redis有设置密码,则加上,没有这行代码去掉
    //        jedis.auth("79797979"); System.out.println(jedis.ping()); } }

    远程连接redis服务器,会出现一些异常

    Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: Failed connecting to host 192.168.223.129:6379

    Caused by: java.net.SocketTimeoutException: connect timed out

    解决:

    防火墙端口号

    cd /etc/sysconfig
    vi iptables
    
    添加以下内容
    -A INPUT -m state --state NEW -m tcp -p tcp --dport 6379 -j ACCEPT

    更改redis的配置文件,bind 127.0.0.1注释掉,任何IP都可以访问redis服务

    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.

    解决:

    更改redis的配置文件,protected-mode yes改为protected-mode no

    重启redis服务

    Jedis的API

    public class TestKey {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.223.129",6379);
            System.out.println("清空当前数据库中的值:" + jedis.flushDB());
            System.out.println("清空所有数据库中的值:" + jedis.flushAll());
            System.out.println("新增键值对:" + jedis.set("key1","value1"));
            System.out.println("新增键值对:" + jedis.set("key2","value2"));
            System.out.println("查看系统中所有的键:" + jedis.keys("*"));
    
            System.out.println("删除键:" + jedis.del("key2"));
            System.out.println("判断某个键是否存在:" + jedis.exists("key2"));
            System.out.println("查看键所存储的值的类型:" + jedis.type("key1"));
            System.out.println("随机返回一个key:" + jedis.randomKey());
            System.out.println("重命名key:" + jedis.rename("key1","key3"));
            System.out.println("按索引查询:" + jedis.select(0));
    
    
            System.out.println("获取key的值:" + jedis.get("key3"));
            System.out.println("返回当前数据库中key的总数:" + jedis.dbSize());
        }
    }
    View Code

    String类型

    public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.223.129",6379);
            jedis.flushDB();
            System.out.println(jedis.set("key1", "value1"));
            System.out.println(jedis.set("key2", "value2"));
            System.out.println(jedis.set("key3", "value3"));
            System.out.println(jedis.set("key4", "value4"));
            System.out.println("删除key2:" + jedis.del("key2"));
            System.out.println("获取key2:" + jedis.get("key2"));
            System.out.println("修改key1:" + jedis.set("key1","modify key1"));
            System.out.println("获取key1:" + jedis.get("key1"));
            System.out.println("在key3值后面追加值:" + jedis.append("key3","append key3"));
            System.out.println("获取key3:" + jedis.get("key3"));
            System.out.println("增加多个键值对:" + jedis.mset("key01","value01","key02","vlaue02"));
            System.out.println("获取多个键值对:" + jedis.mget("key01","key02"));
            System.out.println("删除多个键值对:" + jedis.del("key01","key02"));
            System.out.println("获取多个键值对:" + jedis.mget("key01","key02"));
    
            jedis.flushDB();
            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(jedis.get("key1"));
            System.out.println(jedis.get("key2"));
    
            System.out.println("===========新增键值对 设置有效时间==============");
            System.out.println(jedis.setex("key3",2,"value3"));
            System.out.println(jedis.get("key3"));
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(jedis.get("key3"));
    
            System.out.println("===========获取原值 更新==============");
            System.out.println(jedis.getSet("key2","getset key2"));
            System.out.println(jedis.get("key2"));
    
            System.out.println("获取key2的值的字符串:" + jedis.getrange("key2",2,4));
        }
    View Code

    List类型

    public class TestList {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.223.129",6379);
            jedis.flushDB();
            System.out.println("===========添加list==============");
            jedis.lpush("collections","ArrayLit","Vector","stack","HashMap","WeakHashMap");
            jedis.lpush("collections","HashSet");
            jedis.lpush("collections","TreeSet");
            jedis.lpush("collections","TreeMap");
    
            System.out.println("collections的内容:" + jedis.lrange("collections",0,-1));
            System.out.println("collections区间0-3的元素:" + jedis.lrange("collections",0,3));
    
    
            System.out.println("删除指定元素:" + jedis.lrem("collections",2,"HashMap"));
            System.out.println("collections的内容:" + jedis.lrange("collections",0,-1));
    
            System.out.println("删除下标0-3区间之外的元素:" + jedis.ltrim("collections",0,3));
            System.out.println("collections的内容:" + jedis.lrange("collections",0,-1));
    
            System.out.println("出栈(左进左出):" + jedis.lpop("collections"));
            System.out.println("collections的内容:" + jedis.lrange("collections",0,-1));
    
            System.out.println("添加元素 从列表右端添加:" + jedis.rpush("collections","LinkMap"));
            System.out.println("collections的内容:" + jedis.lrange("collections",0,-1));
    
            System.out.println("出栈(右进右出):" + jedis.rpop("collections"));
            System.out.println("collections的内容:" + jedis.lrange("collections",0,-1));
    
            System.out.println("修改指定下标的内容:" + jedis.lset("collections",1,"Link"));
            System.out.println("collections的内容:" + jedis.lrange("collections",0,-1));
    
            System.out.println("列表的长度:" + jedis.llen("collections"));
            System.out.println("获取指定下标的元素:" + jedis.lindex("collections",2));
    
            jedis.lpush("sortedList","3","6","2","7","0","4");
            System.out.println("排序前:" + jedis.lrange("sortedList",0,-1));
            System.out.println(jedis.sort("sortedList"));
            System.out.println("排序后:" + jedis.lrange("sortedList",0,-1));
    
        }
    }
    View Code

    Set类型

    public class TestSet {
        public static void main(String[] args) {
    
            Jedis jedis = new Jedis("192.168.223.129",6379);
            jedis.flushDB();
            System.out.println("===========添加元素(不重复)==============");
            jedis.sadd("eleSet","e1","e2","e3","e0","e8","e7","e9","e4","e5");
            jedis.sadd("eleSet","e6");
            jedis.sadd("eleSet","e6");
            System.out.println("eleSet的所有成员:" + jedis.smembers("eleSet"));
            System.out.println("eleSet的成员个数:" + jedis.scard("eleSet"));
    
            System.out.println("删除指定成员e0:" + jedis.srem("eleSet","e0"));
            System.out.println("eleSet的所有成员:" + jedis.smembers("eleSet"));
    
            System.out.println("删除指定成员e7和e6:" + jedis.srem("eleSet","e7","e6"));
            System.out.println("eleSet的所有成员:" + jedis.smembers("eleSet"));
    
            System.out.println("随机移除一个成员:" + jedis.spop("eleSet"));
            System.out.println("eleSet的所有成员:" + jedis.smembers("eleSet"));
    
            System.out.println("成员是否存在集合中:" + jedis.sismember("eleSet","e3"));
            System.out.println("eleSet的所有成员:" + jedis.smembers("eleSet"));
    
            System.out.println("=========================");
            System.out.println(jedis.sadd("eleSet1", "e1", "e2", "e3", "e0", "e8", "e7", "e9", "e4", "e5"));
            System.out.println(jedis.sadd("eleSet2", "e1", "e2", "e3", "e0", "e8"));
    
            System.out.println("将指定成员移除,并存储到新的集合中:" + jedis.smove("eleSet1","eleSet3","e1"));
            System.out.println("eleSet1的所有成员:" + jedis.smembers("eleSet1"));
            System.out.println("eleSet3的所有成员:" + jedis.smembers("eleSet3"));
    
            System.out.println("===========集合运算==============");
            System.out.println("eleSet1的所有成员:" + jedis.smembers("eleSet1"));
            System.out.println("eleSet2的所有成员:" + jedis.smembers("eleSet2"));
    
            System.out.println("交集:" + jedis.sinter("eleSet1","eleSet2"));
            System.out.println("并集:" + jedis.sunion("eleSet1","eleSet2"));
            System.out.println("差集:" + jedis.sdiff("eleSet1","eleSet2"));
            System.out.println("交集结果存储到新的集合中:" + jedis.sinterstore("eleSet4","eleSet1","eleSet2"));
            System.out.println("eleSet4的所有成员:" + jedis.smembers("eleSet4"));
        }
    }
    View Code

    Hash类型

    public class TestHash {
        public static void main(String[] args) {
    
            Jedis jedis = new Jedis("192.168.223.129",6379);
            jedis.flushDB();
            System.out.println("===========添加元素==============");
            Map<String,String> map =new HashMap<>();
            map.put("key1","value1");
            map.put("key2","value2");
            map.put("key3","value3");
            map.put("key4","value4");
            jedis.hmset("hash",map);
    
            jedis.hset("hash","key5","value5");
    
            System.out.println("散列hash的所有键值对:" + jedis.hgetAll("hash"));
            System.out.println("散列hash的所有键:" + jedis.hkeys("hash"));
            System.out.println("散列hash的所有值:" + jedis.hvals("hash"));
    
            System.out.println("将key6的值加上一个整数,如果key6不存在则添加key6:" + jedis.hincrBy("hash","key6",6));
            System.out.println("散列hash的所有键值对:" + jedis.hgetAll("hash"));
    
            System.out.println("删除一个或多个键值对:" + jedis.hdel("hash","key2"));
            System.out.println("散列hash的所有键值对:" + jedis.hgetAll("hash"));
    
            System.out.println("散列hash的所有键值对的个数:" + jedis.hlen("hash"));
            System.out.println("判断hash中是否存在key2:" + jedis.hexists("hash","key2"));
            System.out.println("获取指定fields的值:" + jedis.hmget("hash","key3","key4"));
    
        }
    }
    View Code

    事务

    public class TestTX {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.223.129", 6379);
            jedis.flushDB();
    
            //创建json格式的字符串
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("hello","world");
            jsonObject.put("name","yyy");
            String result = jsonObject.toJSONString();
    
            //开启事务
            Transaction multi = jedis.multi();
            try{
                //像redis中存入一条数据
                multi.set("json1",result);
                //在存入一条数据
                multi.set("json2",result);
                //异常模拟
                int i=1/0;
                multi.exec();
            }catch (Exception e){
                multi.discard();//放弃执行
                e.printStackTrace();
            }finally {
                System.out.println("============="+jedis.get("json1"));
                System.out.println("============="+jedis.get("json2"));
                //最终,关闭客户端
                jedis.close();
            }
    
        }
    }
    View Code
  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    HDFS HA高可用
  • 原文地址:https://www.cnblogs.com/WarBlog/p/15245635.html
Copyright © 2011-2022 走看看