精华内容
下载资源
问答
  • JedisCluster密码设置

    千次阅读 2020-12-14 16:58:51
    问题:通过jedisCluster.auth("password"); 报错:redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required 如果是jedis单机模式的话,我们可以直接使用jedis.auth来进行设置 ...

    问题:通过jedisCluster.auth("password");

    报错:redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required 

    如果是jedis单机模式的话,我们可以直接使用jedis.auth来进行设置

    Jedis jedis = new Jedis("127.0.0.1",6379);
    jedis.auth("password");

    但是 jedisCluster.auth("password");查看源码发现只是实现了异常处理,并没有什么用。

    /**
       * @deprecated No key operation doesn't make sense for Redis Cluster and Redis Cluster doesn't
       *             support authorization scheduled to be removed on next major release
       */
      @Deprecated
      @Override
      public String auth(String password) {
        throw new JedisClusterException("No way to dispatch this command to Redis Cluster.");
      }

     查看JedisCluster构造方法发现,有一个这样的

    new JedisCluster(Set<HostAndPort> jedisClusterNode, int connectionTimeout, int soTimeout,int maxAttempts, String password, final GenericObjectPoolConfig poolConfig);

    import java.io.IOException;
    import java.util.HashSet;
    import java.util.Set;
    import redis.clients.jedis.HostAndPort;
    import redis.clients.jedis.JedisCluster;
    import redis.clients.jedis.JedisPoolConfig;
    
    public class GetData {
    	public static void main(String[] args) throws IOException {
    		JedisPoolConfig config = new JedisPoolConfig();
    		config .setMaxTotal(500);
    		config .setMinIdle(2);
    		config .setMaxIdle(500);
    		config .setMaxWaitMillis(10000);
    		config .setTestOnBorrow(true);
    		config .setTestOnReturn(true);	
    		Set<HostAndPort> nodes = new HashSet<>();
    		nodes.add(new HostAndPort("xxxx", 6379));
    		nodes.add(new HostAndPort("xxxx", 6380));
    		nodes.add(new HostAndPort("xxxx", 6381));
    		nodes.add(new HostAndPort("xxxx", 6382));
    		JedisCluster jedis = new JedisCluster(nodes, 10000, 10000, 100, "password", i2);		
    	}		
    }

    解决办法: 通过JedisCluster jedis = new JedisCluster(nodes, 10000, 10000, 100, "password", config);        来设置集群密码:但是jedis版本必须是2.9及以上

     

    展开全文
  • 出现问题:Redis3集群设置了密码,在程序中Jedis2.8 通过JedisCluster 操作redis 系统报错 ```redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required. at redis.clients.jedis....
  • JedisCluster

    2020-11-19 16:45:45
    需要已经集成成功JedisCluster 本人已实践的参考:https://blog.csdn.net/NullToSay/article/details/109813194 二、定义RedisLock类 import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; ...

    一、前置配置

    需要已经集成成功JedisCluster

    本人已实践的参考:https://blog.csdn.net/NullToSay/article/details/109813194

     

    二、定义RedisLock类

    import org.apache.commons.lang.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import redis.clients.jedis.JedisCluster;
    import redis.clients.jedis.exceptions.JedisNoScriptException;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class RedisLock {
    
        private static final Logger log = LoggerFactory.getLogger(RedisLock.class);
    
        private JedisCluster jedisCluster;
    
        /**
         * lua脚本:判断锁住值是否为当前线程持有,是的话解锁,不是的话解锁失败
         */
        private static final String DISTRIBUTE_LOCK_SCRIPT_UNLOCK_VAL = "if" +
                " redis.call('get', KEYS[1]) == ARGV[1]" +
                " then" +
                " return redis.call('del', KEYS[1])" +
                " else" +
                " return 0" +
                " end";
    
        private volatile String unlockSha1 = "";
    
        private static final Long UNLOCK_SUCCESS_CODE = 1L;
    
        private static final String LOCK_SUCCESS_CODE = "ok";
    
        public RedisLock(JedisCluster jedisCluster) {
            this.jedisCluster = jedisCluster;
        }
    
    
        /**
         * 根据loopTryTime循环重试
         * @param lockKey 锁key
         * @param lockVal 锁值,用于解锁校验
         * @param expiryTime 锁过期时间
         * @param loopTryTime 获取失败时,循环重试获取锁的时长
         * @return 是否获得锁
         */
        public boolean lock(String lockKey, String lockVal, long expiryTime, long loopTryTime){
            Long endTime = System.currentTimeMillis() + loopTryTime;
            while (System.currentTimeMillis() < endTime){
                if (lock(lockKey, lockVal, expiryTime)){
                    return true;
                }
            }
            return false;
        }
    
        /**
         * 根据loopTryTime循环重试
         * @param lockKey 锁key
         * @param lockVal 锁值,用于解锁校验
         * @param expiryTime 锁过期时间
         * @param retryTimes 重试次数
         * @param setpTime 每次重试间隔 mills
         * @return 是否获得锁
         */
        public boolean lock(String lockKey, String lockVal, long expiryTime, int retryTimes, long setpTime){
            while (retryTimes > 0){
                if (lock(lockKey, lockVal, expiryTime)){
                    return true;
                }
                retryTimes--;
                try {
                    Thread.sleep(setpTime);
                } catch (InterruptedException e) {
                    log.error("get distribute lock error" +e.getLocalizedMessage());
                }
            }
            return false;
        }
    
        /**
         * 一次尝试,快速失败。不支持重入
         * @param lockKey 锁key
         * @param lockVal 锁值,用于解锁校验
         * @param expiryTime 锁过期时间 MILLS
         * @return 是否获得锁
         */
        public boolean lock(String lockKey, String lockVal, long expiryTime){
            //相比一般的分布式锁,这里把setNx和setExpiry操作合并到一起,jedis保证原子性,避免连个命令之间出现宕机等问题
            //这里也可以我们使用lua脚本实现
            String result = jedisCluster.set(lockKey, lockVal, "NX", "PX", expiryTime);
            return LOCK_SUCCESS_CODE.equalsIgnoreCase(result);
        }
    
        /**
         * 释放分布式锁,释放失败最可能是业务执行时间长于lockKey过期时间,应当结合业务场景调整过期时间
         * @param lockKey 锁key
         * @param lockVal 锁值
         * @return 是否释放成功
         */
        public boolean unLock(String lockKey, String lockVal){
            List<String> keys = new ArrayList<>();
            keys.add(lockKey);
            List<String> argv = new ArrayList<>();
            argv.add(lockVal);
            try {
                Object result = jedisCluster.evalsha(unlockSha1, keys, argv);
                return UNLOCK_SUCCESS_CODE.equals(result);
            }catch (JedisNoScriptException e){
                //没有脚本缓存时,重新发送缓存
                log.info("try to store script......");
                storeScript(lockKey);
                Object result = jedisCluster.evalsha(unlockSha1, keys, argv);
                return UNLOCK_SUCCESS_CODE.equals(result);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 由于使用redis集群,因此每个节点都需要各自缓存一份脚本数据
         * @param slotKey 用来定位对应的slot的slotKey
         */
        private void storeScript(String slotKey){
            if (StringUtils.isEmpty(unlockSha1) || !jedisCluster.scriptExists(unlockSha1, slotKey)){
                //redis支持脚本缓存,返回哈希码,后续可以继续用来调用脚本
                unlockSha1 = jedisCluster.scriptLoad(DISTRIBUTE_LOCK_SCRIPT_UNLOCK_VAL, slotKey);
            }
        }
    
    }

     

    三、对象初始化

    在配置文件内,初始化RedisLock对象(注入JedisCluster)

    @Bean
        //定义分布式锁对象
        public RedisLock redisLock(JedisCluster jedisCluster){
            return new RedisLock(jedisCluster);
        }

     

    最后JedisClusterConfig配置文件变为

    import com.yntrust.tcmp.management.service.utils.RedisLock;
    import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
    import redis.clients.jedis.HostAndPort;
    import redis.clients.jedis.JedisCluster;
    
    import java.util.HashSet;
    import java.util.Set;
    
    @Configuration
    public class JedisClusterConfig {
    
        //redis集群节点列表
        @Value("${spring.redis.cluster.nodes}")
        private String clusterNodes;
    
        //redis集群连接超时时间
        @Value("${spring.redis.cluster.timeout}")
        private Long timeout;
    
        //redis集群最大连接次数
        @Value("${spring.redis.cluster.max-redirects}")
        private int redirects;
    
        //redis集群连接密码
        @Value("${spring.redis.cluster.password}")
        private String password;
    
    
        @Bean
        //重写JedisConnectionFactory方法,注入密码,否则会报认证错误(这个初始化,在getJedisCluster()之前,所以没有读到密码)
        public JedisConnectionFactory connectionFactory(){
            JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
            connectionFactory.setPassword(password);
            return connectionFactory;
        }
    
        @Bean
        //定义分布式锁对象
        public RedisLock redisLock(JedisCluster jedisCluster){
            return new RedisLock(jedisCluster);
        }
    
        @Bean
        //定义JedisCluster对象
        public JedisCluster getJedisCluster(){
            String [] serverArray=clusterNodes.split(",");
            Set<HostAndPort> nodes=new HashSet<>();
    
            for (String ipPort:serverArray){
                String [] ipPortPair=ipPort.split(":");
                nodes.add(new HostAndPort(ipPortPair[0].trim(),Integer.valueOf(ipPortPair[1].trim())));
    
            }
            JedisCluster jedisCluster = new JedisCluster(nodes,timeout.intValue(),timeout.intValue(),redirects,password,new GenericObjectPoolConfig());
    
            return  jedisCluster;
        }
    
    
    
    }

     

    四、使用

    在需要使用锁的业务模块,用

    @Autowired
    private RedisLock redisLock;

    注入使用

     

    展开全文
  • Redis Jedis、jedisCluster的使用

    千次阅读 2018-10-17 11:30:53
    Redis Jedis、jedisCluster的使用 1、Jedis客户端 https://redis.io/clients 2、Jedis源码包与使用介绍 https://github.com/xetorthio/jedis 3、项目中使用 通过maven引入Jedis的依赖包 复制代码 redis.clients ...

    Redis Jedis、jedisCluster的使用

    1、Jedis客户端

    https://redis.io/clients
    2、Jedis源码包与使用介绍

    https://github.com/xetorthio/jedis
    3、项目中使用

    通过maven引入Jedis的依赖包
    复制代码

    redis.clients jedis 2.9.0 jar compile

    复制代码
    4、Jedis的使用

    创建Jedis对象,set方法存储key-value值,get方法获取key对应的值。主要是用于单个redis。

    Jedis jedis = new Jedis(“192.168.56.180”, 6379);
    jedis.set(“Jedis”, “Hello Work!”);
    System.out.println(jedis.get(“Jedis”));
    jedis.close();

    这里是使用IDEA编辑器对Jedis类结构的一个关系图,从图中看出Jedis继承BinaryJedis,实现多个接口。

    每一个接口都代表了一类Redis命令,例如JedisCommands中包含了SET GET等命令,MultiKeyCommands中包含了针对多个Key的MSET MGET等命令。
    5、JedisCluster的使用

    Jediscluster类图和jedis类图大致一样,不过jedisCluster有一些命令是不可用的。比如BinaryJedisCluster类被作废的命令。主要是用在集群中。

    类图:

    6、单个reids中API的测试
    复制代码

    package com.redis;

    import org.junit.Test;
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.SortingParams;

    import java.sql.Timestamp;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.concurrent.TimeUnit;

    /**

    • 单机环境Redis操作:一台Redis服务器
      */
      public class Standalone {
      private static Jedis jedis;
      static {
      jedis = new Jedis(“192.168.56.180”, 6379);
      jedis.auth(“123456”); // 之前我在redis配置中配置了权限密码,这里需要设置
      }

      /**

      • 测试key - value 的数据
      • @throws InterruptedException
        /
        @Test
        public void testKey() throws InterruptedException {
        System.out.println(“清空数据:”+jedis.flushDB());
        System.out.println(“判断某个键是否存在:”+jedis.exists(“username”));
        System.out.println(“新增<‘username’,‘wukong’>的键值对:”+jedis.set(“username”, “wukong”));
        System.out.println(“是否存在:”+jedis.exists(“name”));
        System.out.println(“新增<‘password’,‘password’>的键值对:”+jedis.set(“password”, “password”));
        Set keys = jedis.keys("
        ");
        System.out.println(“系统中所有的键如下:”+keys);
        System.out.println(“删除键password:”+jedis.del(“password”));
        System.out.println(“判断键password是否存在:”+jedis.exists(“password”));
        System.out.println(“设置键username的过期时间为5s:”+jedis.expire(“username”, 5));
        TimeUnit.SECONDS.sleep(2);
        System.out.println(“查看键username的剩余生存时间:”+jedis.ttl(“username”));
        System.out.println(“移除键username的生存时间:”+jedis.persist(“username”));
        System.out.println(“查看键username的剩余生存时间:”+jedis.ttl(“username”));
        System.out.println(“查看键username所存储的值的类型:”+jedis.type(“username”));
        }

      /***

      • 字符串操作

      • memcached和redis同样有append的操作,但是memcached有prepend的操作,redis中并没有。

      • @throws InterruptedException
        */
        @Test
        public void testString() throws InterruptedException {
        jedis.flushDB();
        System.out.println("=增加数据=");
        System.out.println(jedis.set(“key1”,“value1”));
        System.out.println(jedis.set(“key2”,“value2”));
        System.out.println(jedis.set(“key3”, “value3”));
        System.out.println(“删除键key2:”+jedis.del(“key2”));
        System.out.println(“获取键key2:”+jedis.get(“key2”));
        System.out.println(“修改key1:”+jedis.set(“key1”, “value1Changed”));
        System.out.println(“获取key1的值:”+jedis.get(“key1”));
        System.out.println(“在key3后面加入值:”+jedis.append(“key3”, “End”));
        System.out.println(“key3的值:”+jedis.get(“key3”));
        System.out.println(“增加多个键值对:”+jedis.mset(“key01”,“value01”,“key02”,“value02”,“key03”,“value03”));
        System.out.println(“获取多个键值对:”+jedis.mget(“key01”,“key02”,“key03”));
        System.out.println(“获取多个键值对:”+jedis.mget(“key01”,“key02”,“key03”,“key04”));
        System.out.println(“删除多个键值对:”+jedis.del(new String[]{“key01”,“key02”}));
        System.out.println(“获取多个键值对:”+jedis.mget(“key01”,“key02”,“key03”));

        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”));
        TimeUnit.SECONDS.sleep(3);
        System.out.println(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(jedis.get(“key2”));

        System.out.println(“获得key2的值的字串:”+jedis.getrange(“key2”, 2, 4));
        }

      /***

      • 整数和浮点数
        */
        @Test
        public void testNumber() {
        jedis.flushDB();
        jedis.set(“key1”, “1”);
        jedis.set(“key2”, “2”);
        jedis.set(“key3”, “2.3”);
        System.out.println(“key1的值:”+jedis.get(“key1”));
        System.out.println(“key2的值:”+jedis.get(“key2”));
        System.out.println(“key1的值加1:”+jedis.incr(“key1”));
        System.out.println(“获取key1的值:”+jedis.get(“key1”));
        System.out.println(“key2的值减1:”+jedis.decr(“key2”));
        System.out.println(“获取key2的值:”+jedis.get(“key2”));
        System.out.println(“将key1的值加上整数5:”+jedis.incrBy(“key1”, 5));
        System.out.println(“获取key1的值:”+jedis.get(“key1”));
        System.out.println(“将key2的值减去整数5:”+jedis.decrBy(“key2”, 5));
        System.out.println(“获取key2的值:”+jedis.get(“key2”));
        }

      /***

      • 列表
        */
        @Test
        public void testList() {
        jedis.flushDB();
        System.out.println("=添加一个list=");
        jedis.lpush(“collections”, “ArrayList”, “Vector”, “Stack”, “HashMap”, “WeakHashMap”, “LinkedHashMap”);
        jedis.lpush(“collections”, “HashSet”);
        jedis.lpush(“collections”, “TreeSet”);
        jedis.lpush(“collections”, “TreeMap”);
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));//-1代表倒数第一个元素,-2代表倒数第二个元素
        System.out.println(“collections区间0-3的元素:”+jedis.lrange(“collections”,0,3));
        System.out.println("=");
        // 删除列表指定的值 ,第二个参数为删除的个数(有重复时),后add进去的值先被删,类似于出栈
        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(“collections列表出栈(左端):”+jedis.lpop(“collections”));
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        System.out.println(“collections添加元素,从列表右端,与lpush相对应:”+jedis.rpush(“collections”, “EnumMap”));
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        System.out.println(“collections列表出栈(右端):”+jedis.rpop(“collections”));
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        System.out.println(“修改collections指定下标1的内容:”+jedis.lset(“collections”, 1, “LinkedArrayList”));
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        System.out.println("
        =");
        System.out.println(“collections的长度:”+jedis.llen(“collections”));
        System.out.println(“获取collections下标为2的元素:”+jedis.lindex(“collections”, 2));
        System.out.println("===============================");
        jedis.lpush(“sortedList”, “3”,“6”,“2”,“0”,“7”,“4”);
        System.out.println(“sortedList排序前:”+jedis.lrange(“sortedList”, 0, -1));
        System.out.println(jedis.sort(“sortedList”));
        System.out.println(“sortedList排序后:”+jedis.lrange(“sortedList”, 0, -1));
        }

      /***

      • set集合
        */
        @Test
        public void testSet() {
        jedis.flushDB();
        System.out.println(“向集合中添加元素”);
        System.out.println(jedis.sadd(“eleSet”, “e1”,“e2”,“e4”,“e3”,“e0”,“e8”,“e7”,“e5”));
        System.out.println(jedis.sadd(“eleSet”, “e6”));
        System.out.println(jedis.sadd(“eleSet”, “e6”));
        System.out.println(“eleSet的所有元素为:”+jedis.smembers(“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(“随机的移除集合中的一个元素:”+jedis.spop(“eleSet”));
        System.out.println(“eleSet的所有元素为:”+jedis.smembers(“eleSet”));
        System.out.println(“eleSet中包含元素的个数:”+jedis.scard(“eleSet”));
        System.out.println(“e3是否在eleSet中:”+jedis.sismember(“eleSet”, “e3”));
        System.out.println(“e1是否在eleSet中:”+jedis.sismember(“eleSet”, “e1”));
        System.out.println(“e1是否在eleSet中:”+jedis.sismember(“eleSet”, “e5”));
        System.out.println("=============================");
        System.out.println(jedis.sadd(“eleSet1”, “e1”,“e2”,“e4”,“e3”,“e0”,“e8”,“e7”,“e5”));
        System.out.println(jedis.sadd(“eleSet2”, “e1”,“e2”,“e4”,“e3”,“e0”,“e8”));
        System.out.println(“将eleSet1中删除e1并存入eleSet3中:”+jedis.smove(“eleSet1”, “eleSet3”, “e1”));
        System.out.println(“将eleSet1中删除e2并存入eleSet3中:”+jedis.smove(“eleSet1”, “eleSet3”, “e2”));
        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(“eleSet1和eleSet2的交集:”+jedis.sinter(“eleSet1”,“eleSet2”));
        System.out.println(“eleSet1和eleSet2的并集:”+jedis.sunion(“eleSet1”,“eleSet2”));
        System.out.println(“eleSet1和eleSet2的差集:”+jedis.sdiff(“eleSet1”,“eleSet2”));//eleSet1中有,eleSet2中没有
        }

      /***

      • 散列
        */
        @Test
        public void testHash() {
        jedis.flushDB();
        Map<String,String> map = new HashMap<String,String>();
        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”));//return Map<String,String>
        System.out.println(“散列hash的所有键为:”+jedis.hkeys(“hash”));//return Set
        System.out.println(“散列hash的所有值为:”+jedis.hvals(“hash”));//return List
        System.out.println(“将key6保存的值加上一个整数,如果key6不存在则添加key6:”+jedis.hincrBy(“hash”, “key6”, 6));
        System.out.println(“散列hash的所有键值对为:”+jedis.hgetAll(“hash”));
        System.out.println(“将key6保存的值加上一个整数,如果key6不存在则添加key6:”+jedis.hincrBy(“hash”, “key6”, 3));
        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(“判断hash中是否存在key3:”+jedis.hexists(“hash”,“key3”));
        System.out.println(“获取hash中的值:”+jedis.hmget(“hash”,“key3”));
        System.out.println(“获取hash中的值:”+jedis.hmget(“hash”,“key3”,“key4”));
        }

      /**

      • 有序集合
        */
        @Test
        public void testSortedSet() {
        jedis.flushDB();
        Map<String,Double> map = new HashMap<String,Double>();
        map.put(“key2”,1.2);
        map.put(“key3”,4.0);
        map.put(“key4”,5.0);
        map.put(“key5”,0.2);
        System.out.println(jedis.zadd(“zset”, 3,“key1”));
        System.out.println(jedis.zadd(“zset”,map));
        System.out.println(“zset中的所有元素:”+jedis.zrange(“zset”, 0, -1));
        System.out.println(“zset中的所有元素:”+jedis.zrangeWithScores(“zset”, 0, -1));
        System.out.println(“zset中的所有元素:”+jedis.zrangeByScore(“zset”, 0,100));
        System.out.println(“zset中的所有元素:”+jedis.zrangeByScoreWithScores(“zset”, 0,100));
        System.out.println(“zset中key2的分值:”+jedis.zscore(“zset”, “key2”));
        System.out.println(“zset中key2的排名:”+jedis.zrank(“zset”, “key2”));
        System.out.println(“删除zset中的元素key3:”+jedis.zrem(“zset”, “key3”));
        System.out.println(“zset中的所有元素:”+jedis.zrange(“zset”, 0, -1));
        System.out.println(“zset中元素的个数:”+jedis.zcard(“zset”));
        System.out.println(“zset中分值在1-4之间的元素的个数:”+jedis.zcount(“zset”, 1, 4));
        System.out.println(“key2的分值加上5:”+jedis.zincrby(“zset”, 5, “key2”));
        System.out.println(“key3的分值加上4:”+jedis.zincrby(“zset”, 4, “key3”));
        System.out.println(“zset中的所有元素:”+jedis.zrange(“zset”, 0, -1));
        }

      /**

      • 排序
        /
        @Test
        public void testSort()
        {
        jedis.flushDB();
        jedis.lpush(“collections”, “ArrayList”, “Vector”, “Stack”, “HashMap”, “WeakHashMap”, “LinkedHashMap”);
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        SortingParams sortingParameters = new SortingParams();
        System.out.println(jedis.sort(“collections”,sortingParameters.alpha()));
        System.out.println("=");
        jedis.lpush(“sortedList”, “3”,“6”,“2”,“0”,“7”,“4”);
        System.out.println(“sortedList排序前:”+jedis.lrange(“sortedList”, 0, -1));
        System.out.println(“升序:”+jedis.sort(“sortedList”, sortingParameters.asc()));
        System.out.println(“升序:”+jedis.sort(“sortedList”, sortingParameters.desc()));
        System.out.println("
        =");
        jedis.lpush(“userlist”, “33”);
        jedis.lpush(“userlist”, “22”);
        jedis.lpush(“userlist”, “55”);
        jedis.lpush(“userlist”, “11”);
        jedis.hset(“user:66”, “name”, “66”);
        jedis.hset(“user:55”, “name”, “55”);
        jedis.hset(“user:33”, “name”, “33”);
        jedis.hset(“user:22”, “name”, “79”);
        jedis.hset(“user:11”, “name”, “24”);
        jedis.hset(“user:11”, “add”, “beijing”);
        jedis.hset(“user:22”, “add”, “shanghai”);
        jedis.hset(“user:33”, “add”, “guangzhou”);
        jedis.hset(“user:55”, “add”, “chongqing”);
        jedis.hset(“user:66”, “add”, “xi’an”);
        sortingParameters = new SortingParams();
        sortingParameters.get("user:
        ->name");
        sortingParameters.get(“user:*->add”);
        System.out.println(jedis.sort(“userlist”,sortingParameters));
        }
        }

    复制代码
    7、集群reids中API的测试
    复制代码

    package com.redis;

    import org.junit.Test;
    import redis.clients.jedis.HostAndPort;
    import redis.clients.jedis.JedisCluster;
    import redis.clients.jedis.JedisPoolConfig;
    import redis.clients.jedis.SortingParams;

    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;

    /**

    • 集群环境下Jedis操作
      */
      public class Cluster {
      private static JedisCluster jedis;
      static {
      // 添加集群的服务节点Set集合
      Set hostAndPortsSet = new HashSet();
      // 添加节点
      hostAndPortsSet.add(new HostAndPort(“192.168.56.180”, 7777));
      hostAndPortsSet.add(new HostAndPort(“192.168.56.180”, 8888));
      hostAndPortsSet.add(new HostAndPort(“192.168.56.181”, 7777));
      hostAndPortsSet.add(new HostAndPort(“192.168.56.181”, 8888));
      hostAndPortsSet.add(new HostAndPort(“192.168.56.182”, 7777));
      hostAndPortsSet.add(new HostAndPort(“192.168.56.182”, 8888));

       // Jedis连接池配置
       JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
       // 最大空闲连接数, 默认8个
       jedisPoolConfig.setMaxIdle(100);
       // 最大连接数, 默认8个
       jedisPoolConfig.setMaxTotal(500);
       //最小空闲连接数, 默认0
       jedisPoolConfig.setMinIdle(0);
       // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
       jedisPoolConfig.setMaxWaitMillis(2000); // 设置2秒
       //对拿到的connection进行validateObject校验
       jedisPoolConfig.setTestOnBorrow(true);
       jedis = new JedisCluster(hostAndPortsSet, jedisPoolConfig);
      

      }

      /**

      • 测试key:value数据
      • 集群中flushDB、keys废弃
        /
        @Test
        public void testKey() throws InterruptedException {
        //System.out.println(“清空数据:”+jedis.flushDB());
        System.out.println(“判断某个键是否存在:”+jedis.exists(“username”));
        System.out.println(“新增<‘username’,‘wukong’>的键值对:”+jedis.set(“username”, “xiaohai”));
        System.out.println(“是否存在:”+jedis.exists(“username”));
        System.out.println(“新增<‘password’,‘password’>的键值对:”+jedis.set(“password”, “123456”));
        //Set keys = jedis.keys("
        ");
        // System.out.println(“系统中所有的键如下:”+keys);
        System.out.println(“删除键password:”+jedis.del(“password”));
        System.out.println(“判断键password是否存在:”+jedis.exists(“password”));
        System.out.println(“设置键username的过期时间为10s:”+jedis.expire(“username”, 10));
        TimeUnit.SECONDS.sleep(2); // 线程睡眠2秒System.out.println(“查看键username的剩余生存时间:”+jedis.ttl(“username”));
        System.out.println(“查看键username的剩余生存时间:”+jedis.ttl(“username”));
        System.out.println(“移除键username的生存时间:”+jedis.persist(“username”));
        System.out.println(“查看键username的剩余生存时间:”+jedis.ttl(“username”));
        System.out.println(“查看键username所存储的值的类型:”+jedis.type(“username”));
        }

      /***

      • 字符串操作

      • memcached和redis同样有append的操作,但是memcached有prepend的操作,redis中并没有。

      • 集群中flushDB、keys、del(多个值)、mset(多个值)废弃

      • @throws InterruptedException
        */
        @Test
        public void testString() throws InterruptedException {
        //jedis.flushDB();
        System.out.println("=增加数据=");
        System.out.println(jedis.set(“key1”,“value1”));
        System.out.println(jedis.set(“key2”,“value2”));
        System.out.println(jedis.set(“key3”, “value3”));
        System.out.println(“删除键key2:”+jedis.del(“key2”));
        System.out.println(“获取键key2:”+jedis.get(“key2”));
        System.out.println(“修改key1:”+jedis.set(“key1”, “value1Changed”));
        System.out.println(“获取key1的值:”+jedis.get(“key1”));
        System.out.println(“在key3后面加入值:”+jedis.append(“key3”, “End”));
        System.out.println(“key3的值:”+jedis.get(“key3”));
        //命令的时候才会去连接连接,集群中连接是对一个节点连接,不能判断多个key经过crc16算法所对应的槽在一个节点上,不支持多key获取、删除
        //System.out.println(“增加多个键值对:”+jedis.mset(“key01”,“value01”,“key02”,“value02”));
        //System.out.println(“获取多个键值对:”+jedis.mget(“key01”,“key02”,“key03”));
        //System.out.println(“获取多个键值对:”+jedis.mget(“key01”,“key02”,“key03”,“key04”));
        //System.out.println(“删除多个键值对:”+jedis.del(new String[]{“key01”,“key02”}));
        //System.out.println(“获取多个键值对:”+jedis.mget(“key01”,“key02”,“key03”));

        //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”));
        TimeUnit.SECONDS.sleep(3);
        System.out.println(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(jedis.get(“key2”));
        System.out.println(“获得key2的值的字串:”+jedis.getrange(“key2”, 2, 4)); // 相当截取字符串的第二个位置-第四个位置的字符串
        }

      /***

      • 整数和浮点数
        */
        @Test
        public void testNumber() {
        jedis.set(“key1”, “1”);
        jedis.set(“key2”, “2”);
        jedis.set(“key3”, “2.3”);
        System.out.println(“key1的值:”+jedis.get(“key1”));
        System.out.println(“key2的值:”+jedis.get(“key2”));
        System.out.println(“key1的值加1:”+jedis.incr(“key1”));
        System.out.println(“获取key1的值:”+jedis.get(“key1”));
        System.out.println(“key2的值减1:”+jedis.decr(“key2”));
        System.out.println(“获取key2的值:”+jedis.get(“key2”));
        System.out.println(“将key1的值加上整数5:”+jedis.incrBy(“key1”, 5));
        System.out.println(“获取key1的值:”+jedis.get(“key1”));
        System.out.println(“将key2的值减去整数5:”+jedis.decrBy(“key2”, 5));
        System.out.println(“获取key2的值:”+jedis.get(“key2”));
        System.out.println(“key3的值:”+jedis.get(“key3”));
        // 这里会报错,因为key3不是整数不能做计算:redis.clients.jedis.exceptions.JedisDataException: ERR value is not an integer or out of range
        // System.out.println(“key2的值减1:”+jedis.decr(“key3”));
        }

      /***

      • 列表
        */
        @Test
        public void testList() {
        System.out.println("=添加一个list=");
        jedis.lpush(“collections”, “ArrayList”, “Vector”, “Stack”, “HashMap”, “WeakHashMap”, “LinkedHashMap”);
        jedis.lpush(“collections”, “HashSet”); // 叠加
        jedis.lpush(“collections”, “TreeSet”); // 叠加
        jedis.lpush(“collections”, “TreeMap”); // 叠加
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));//-1代表倒数第一个元素,-2代表倒数第二个元素
        System.out.println(“collections区间0-3的元素:”+jedis.lrange(“collections”,0,3)); // 前面4个值
        System.out.println("=");
        // 删除列表指定的值 ,第二个参数为删除的个数(有重复时),后add进去的值先被删,类似于出栈
        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(“collections列表出栈(左端):”+jedis.lpop(“collections”));
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        System.out.println(“collections添加元素,从列表右端,与lpush相对应:”+jedis.rpush(“collections”, “EnumMap”));
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        System.out.println(“collections列表出栈(右端):”+jedis.rpop(“collections”));
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        System.out.println(“修改collections指定下标1的内容:”+jedis.lset(“collections”, 1, “LinkedArrayList”));
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        System.out.println("
        =");
        System.out.println(“collections的长度:”+jedis.llen(“collections”));
        System.out.println(“获取collections下标为2的元素:”+jedis.lindex(“collections”, 2));
        System.out.println("===============================");
        jedis.lpush(“sortedList”, “3”,“6”,“2”,“0”,“7”,“4”);
        System.out.println(“sortedList排序前:”+jedis.lrange(“sortedList”, 0, -1));
        System.out.println(jedis.sort(“sortedList”));
        System.out.println(“sortedList排序后:”+jedis.lrange(“sortedList”, 0, -1));
        }

      /***

      • set集合
        */
        @Test
        public void testSet() {
        System.out.println(“向集合中添加元素”);
        System.out.println(jedis.sadd(“eleSet”, “e1”,“e2”,“e4”,“e3”,“e0”,“e8”,“e7”,“e5”));
        System.out.println(jedis.sadd(“eleSet”, “e6”));
        System.out.println(jedis.sadd(“eleSet”, “e6”)); // 返回0,集合中已经存在
        System.out.println(“eleSet的所有元素为:”+jedis.smembers(“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(“随机的移除集合中的一个元素:”+jedis.spop(“eleSet”));
        System.out.println(“eleSet的所有元素为:”+jedis.smembers(“eleSet”));
        System.out.println(“eleSet中包含元素的个数:”+jedis.scard(“eleSet”));
        System.out.println(“e3是否在eleSet中:”+jedis.sismember(“eleSet”, “e3”));
        System.out.println(“e1是否在eleSet中:”+jedis.sismember(“eleSet”, “e1”));
        System.out.println(“e5是否在eleSet中:”+jedis.sismember(“eleSet”, “e5”));

        // 集群下并存会报错:redis.clients.jedis.exceptions.JedisClusterException: No way to dispatch this command to Redis Cluster because keys have different slots.
        // Redis集群,从key1集合与key2集合并存、交集、差集,两个键经过crc16算法可能有不同的槽。
        /*System.out.println("=================================");
        System.out.println(jedis.sadd(“eleSet1”, “e1”,“e2”,“e4”,“e3”,“e0”,“e8”,“e7”,“e5”));
        System.out.println(jedis.sadd(“eleSet2”, “e1”,“e2”,“e4”,“e3”,“e0”,“e8”));
        System.out.println(“将eleSet1中删除e1并存入eleSet3中:”+jedis.smove(“eleSet1”, “eleSet3”, “e1”));
        System.out.println(“将eleSet1中删除e2并存入eleSet3中:”+jedis.smove(“eleSet1”, “eleSet3”, “e2”));
        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(“eleSet1和eleSet2的交集:”+jedis.sinter(“eleSet1”,“eleSet2”));
        System.out.println(“eleSet1和eleSet2的并集:”+jedis.sunion(“eleSet1”,“eleSet2”));
        System.out.println(“eleSet1和eleSet2的差集:”+jedis.sdiff(“eleSet1”,“eleSet2”));*/
        jedis.del(“eleSet”);
        jedis.del(“eleSet1”);
        jedis.del(“eleSet2”);
        jedis.del(“eleSet3”);
        }

      /***

      • 散列
        */
        @Test
        public void testHash() {
        Map<String,String> map = new HashMap<String,String>();
        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”));//return Map<String,String>
        System.out.println(“散列hash的所有键为:”+jedis.hkeys(“hash”));//return Set
        System.out.println(“散列hash的所有值为:”+jedis.hvals(“hash”));//return List
        System.out.println(“将key6保存的值加上一个整数,如果key6不存在则添加key6:”+jedis.hincrBy(“hash”, “key6”, 6));
        System.out.println(“散列hash的所有键值对为:”+jedis.hgetAll(“hash”));
        System.out.println(“将key6保存的值加上一个整数,如果key6不存在则添加key6:”+jedis.hincrBy(“hash”, “key6”, 3));
        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(“判断hash中是否存在key3:”+jedis.hexists(“hash”,“key3”));
        System.out.println(“获取hash中的值:”+jedis.hmget(“hash”,“key3”));
        System.out.println(“获取hash中的值:”+jedis.hmget(“hash”,“key3”,“key4”));
        }

      /**

      • 有序集合
        */
        @Test
        public void testSortedSet() {
        Map<String,Double> map = new HashMap<String,Double>();
        map.put(“key2”,1.2);
        map.put(“key3”,4.0);
        map.put(“key4”,5.0);
        map.put(“key5”,0.2);
        // 将一个或多个 member 元素及其 score 值加入到有序集 key 当中,如果某个 member 已经是有序集的成员,那么更新这个 member 的 score 值
        // score 值可以是整数值或双精度浮点数
        System.out.println(jedis.zadd(“zset”, 3,“key1”));
        System.out.println(jedis.zadd(“zset”,map));
        System.out.println(“zset中的所有元素:”+jedis.zrange(“zset”, 0, -1));
        System.out.println(“zset中的所有元素:”+jedis.zrangeWithScores(“zset”, 0, -1));
        System.out.println(“zset中的所有元素:”+jedis.zrangeByScore(“zset”, 0,100));
        System.out.println(“zset中的所有元素:”+jedis.zrangeByScoreWithScores(“zset”, 0,100));
        System.out.println(“zset中key2的分值:”+jedis.zscore(“zset”, “key2”));
        System.out.println(“zset中key2的排名:”+jedis.zrank(“zset”, “key2”));
        System.out.println(“删除zset中的元素key3:”+jedis.zrem(“zset”, “key3”));
        System.out.println(“zset中的所有元素:”+jedis.zrange(“zset”, 0, -1));
        System.out.println(“zset中元素的个数:”+jedis.zcard(“zset”));
        System.out.println(“zset中分值在1-4之间的元素的个数:”+jedis.zcount(“zset”, 1, 4));
        System.out.println(“key2的分值加上5:”+jedis.zincrby(“zset”, 5, “key2”));
        System.out.println(“key3的分值加上4:”+jedis.zincrby(“zset”, 4, “key3”));
        System.out.println(“zset中的所有元素:”+jedis.zrange(“zset”, 0, -1));
        }

      /**

      • 排序
        /
        @Test
        public void testSort() {
        jedis.lpush(“collections”, “ArrayList”, “Vector”, “Stack”, “HashMap”, “WeakHashMap”, “LinkedHashMap”);
        System.out.println(“collections的内容:”+jedis.lrange(“collections”, 0, -1));
        SortingParams sortingParameters = new SortingParams();
        // 当数据集中保存的是字符串值时,你可以用 ALPHA,默认是升序
        System.out.println(“alpha排序方式:” + jedis.sort(“collections”,sortingParameters.alpha()));
        System.out.println("=");
        jedis.lpush(“sortedList”, “3”,“6”,“2”,“0”,“7”,“4”);
        System.out.println(“sortedList排序前:”+jedis.lrange(“sortedList”, 0, -1));
        System.out.println(“升序:”+jedis.sort(“sortedList”, sortingParameters.asc()));
        System.out.println(“降序:”+jedis.sort(“sortedList”, sortingParameters.desc()));
        System.out.println("
        =");
        // 集群下不支持分割表排序
        /jedis.lpush(“userlist”, “33”);
        jedis.lpush(“userlist”, “22”);
        jedis.lpush(“userlist”, “55”);
        jedis.lpush(“userlist”, “11”);
        jedis.hset(“user:66”, “name”, “66”);
        jedis.hset(“user:55”, “name”, “55”);
        jedis.hset(“user:33”, “name”, “33”);
        jedis.hset(“user:22”, “name”, “79”);
        jedis.hset(“user:11”, “name”, “24”);
        jedis.hset(“user:11”, “add”, “beijing”);
        jedis.hset(“user:22”, “add”, “shanghai”);
        jedis.hset(“user:33”, “add”, “guangzhou”);
        jedis.hset(“user:55”, “add”, “chongqing”);
        jedis.hset(“user:66”, “add”, “xi’an”);
        sortingParameters = new SortingParams();
        // 符号 “->” 用于分割哈希表的键名(key name)和索引域(hash field),格式为 “key->field”
        sortingParameters.get("user:
        ->name");
        sortingParameters.get("user:
        ->add");
        System.out.println(jedis.sort(“userlist”,sortingParameters));*/
        }
        }
    展开全文
  • 【精】搭建redis cluster集群,JedisCluster密码访问【解决当中各种坑】! 2017年05月09日 00:13:18冉椿林博客阅读数:18208 版权声明:本文为博主原创文章,转载请看官大人注明出处: ...

     

    转:


    【精】搭建redis cluster集群,JedisCluster带密码访问【解决当中各种坑】!

     版权声明:本文为博主原创文章,转载请看官大人注明出处: https://blog.csdn.net/localhost01/article/details/71436801
    一.搭建redis单机
    本文搭建redis3.0版本,3.0主要增加了redis cluster集群功能。
     
    1.下载地址:http://download.redis.io/releases/redis-3.0.0.tar.gz,将下载文件拷贝到/usr/local
     
    2.解压源码:tar -zxvf redis-3.0.0.tar.gz
     
    3.编译源码:cd /usr/local/redis-3.0.0
    make
     
    4.安装到指定目录: cd /usr/local/redis-3.0.0 
    make PREFIX=/usr/local/redis install
     
    5.进入源码目录,将redis.conf拷贝到安装路径:cd /usr/local/redis
    mkdir conf
    cp /usr/local/redis-3.0.0/redis.conf  /usr/local/redis/bin
     
    6.修改redis.conf配置文件,以后端模式启动:daemonize yes
     
    7.启动redis:cd /usr/local/redis ./bin/redis-server ./redis.conf  //在何处启动的server,一些配置文件就默认在该处生成(如果配置的相对路径)
     
    8.redis.conf配置文件主要配置:
    port 7001  //监听的端口
    # bind 127.0.0.1  //绑定ip,只允许该ip访问,不填默认为*,表示允许所有ip访问
    requirepass "你的密码"  //开启密码
    loglevel debug   //日志级别,开发模式尽量选用debug
    logfile "redis.log"   //日志文件路径,此处使用相对路径,将生成到/usr/local/redis下
    maxmemory 100000000  //允许最大内存占用100m
    appendonly yes  //启用aof
    auto-aof-rewrite-percentage 80  //部署在同一机器的多个redis实例,建议把auto-aof-rewrite错开(可分别写80-100不等),防止瞬间fork,所有redis进程做rewrite,占用大量内存
     
    9.jedis连接redis单机:
    1. <dependency>
    2. <groupId>redis.clients</groupId>
    3. <artifactId>jedis</artifactId>
    4. <version>2.7.0</version>
    5. </dependency>
    1. 连接池整合spring:
    2. <!-- redis连接池(单例) -->
    3. <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="close">
    4. <constructor-arg name="poolConfig" ref="jedisPoolConfig"/>
    5. <constructor-arg name="host" value="${redis.host}"/>
    6. <constructor-arg name="port" value="${redis.port}"/>
    7. <constructor-arg name="timeout" value="${redis.timeout}"/>
    8. <constructor-arg name="password" value="${redis.pass}"/>
    9. </bean>
    1. <!-- 连接池配置 -->
    2. <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
    3. <!-- 最大连接数 -->
    4. <property name="maxTotal" value="150" />
    5. <!-- 最大空闲连接数 -->
    6. <property name="maxIdle" value="30" />
    7. <!-- 最小空闲连接数 -->
    8. <property name="minIdle" value="10" />
    9. <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
    10. <property name="maxWaitMillis" value="3000" />
    11. <!-- 每次释放连接的最大数目 -->
    12. <property name="numTestsPerEvictionRun" value="100" />
    13. <!-- 释放连接的扫描间隔(毫秒) -->
    14. <property name="timeBetweenEvictionRunsMillis" value="3000" />
    15. <!-- 连接最小空闲时间 -->
    16. <property name="minEvictableIdleTimeMillis" value="1800000" />
    17. <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
    18. <property name="softMinEvictableIdleTimeMillis" value="10000" />
    19. <!-- 在获取连接的时候检查有效性, 默认false -->
    20. <property name="testOnBorrow" value="true" />
    21. <!-- 在空闲时检查有效性, 默认false -->
    22. <property name="testWhileIdle" value="true" />
    23. <!-- 在归还给pool时,是否提前进行validate操作 -->
    24. <property name="testOnReturn" value="true" />
    25. <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
    26. <property name="blockWhenExhausted" value="false" />
    27. </bean>
    1. @RunWith(SpringJUnit4ClassRunner.class) // 指定测试用例的运行器 这里是指定了Junit4
    2. @ContextConfiguration("classpath:spring/application*.xml")
    3. public class RedisTest {
    4. @Autowired
    5. private JedisPool pool;
    6. @Test
    7. public void testJedisPool() {
    8. Jedis jedis = null;
    9. String name = null;
    10. try {
    11. jedis = pool.getResource();
    12. jedis.set("testName", "RCL");
    13. name = jedis.get("testName");
    14. } catch (Exception ex) {
    15. ex.printStackTrace();
    16. } finally {
    17. if (jedis != null) {
    18. // 返回给池
    19. jedis.close();
    20. }
    21. Assert.assertEquals("RCL", name);
    22. }
    23. }
    10.如果连接不上,可查看是否防火墙没有将redis端口开放:/etc/sysconfig/iptables添加:
    -A INPUT -p tcp -m state --state NEW -m tcp --dport 7001 -j ACCEPT //7001即redis端口
    重启防火墙
     
     
    二、搭建redis集群
    1.安装ruby环境
    集群管理工具redis-trib.rb依赖ruby环境
    (1)安装ruby:
    yum install ruby yum install rubygems
    (2)安装ruby和redis的接口程序:
    拷贝redis-3.0.0.gem至/usr/local。执行:gem install /usr/local/redis-3.0.0.gem
     
    2.建立redis实例
    (1)建立存放redis群的文件夹及子文件夹(用于存放每个redis实例):
    cd /usr/local    
    mkdir redis-cluster 
    mkdir redis-cluster/7001
    mkdir redis-cluster/7002
    ……
    (2)将刚刚安装的单机redis的/usr/local/redis文件夹拷贝到每个700X文件夹下,(这里我们建立六个实例,三主三从)
    (3)修改每个700X目录下的redis.conf配置文件:
    port 700X   //各自监听的端口
    #bind 127.0.0.1  //这里不绑定,默认允许所有ip访问,或者bind 0.0.0.0
    cluster-enabled yes   //开启集群
    cluster-node-timeout 15000   //15时间内没有收到对方的回复,则单方面认为端节点挂掉
    另外,由于下面我们需要配置集群密码,故之前配置的 requirepass 先删掉,集群成功后再进行配置。
     
    3.启动各个redis:分别进入7001、7002、...7006目录,执行./redis-server ./redis.conf
     
    4.创建集群:/usr/local/redis-cluster/redis-trib.rb create --replicas 1 123.123.123.123:7001 123.123.123.123:7002 123.123.123.123:7003 123.123.123.123:7004 123.123.123.123:7005 123.123.123.123:7006
    注意:
    (1)为保证远程可访问,这里的ip尽量使用公网ip,且创建集群时可先关闭防火墙,否则可以出现一直join……的现象。
    (2)redis集群至少需要3个主节点,每个主节点有一个从节点总共6个节点
    (3)replicas指定为1表示每个主节点有一个从节点
    (4)如果出现[ERR] Sorry, can't connect to node错误:
    1.ruby 和rubygem 版本太低,安装新版本。查看gem版本和redis版本(redis-cli -v可查看redis版本)
    2.查看reids配置文件,bind绑定的允许连接的ip是否正确。
    3.是否redis配置文件还是使用了密码,使用了密码也可能导致这个错误。
    (5)如果出现[ERR] Node 127.0.0.1:7005 is not empty. Either the node already knows other nodes (check with CLUSTER NODES) or contains some key in database 0:
    表示集群时,之前的redis已有数据,那么登录到7005的redis中,执行FLUSHALL即可
    (6)如果出现ERR Slot 0 is already busy (Redis::CommandError):
    用redis-cli登录到每个节点执行flushall和cluster reset即可2.6进入集群:./redis-cli -c  -p 7001 -h 123.123.123.123(-c即-cluster 表示进入集群模式,不加表示进入单机redis)
     
    5.检查集群是否成功:进入集群后,键入cluster info,显示cluster_state:ok,表示成功
     
    6.设置密码:
    (1)登录到每个节点,执行 config set masterauth 你的密码 config set requirepass 你的密码
    (2)随后登入 7001/bin/redis-cli -c -h 112.74.55.239 -p 7004 -a 你的密码,执行: config rewrite
    (3)防火墙开放7001到7006端口,以及redis总线:17001到17006:
    -A INPUT -p tcp -m state --state NEW -m tcp --dport 7001:7006 -j ACCEPT
    -A INPUT -p tcp -m state --state NEW -m tcp --dport 17001:17006 -j ACCEPT
     
    7.JedisCluster连接redis集群
    1. <dependency>
    2. <groupId>redis.clients</groupId>
    3. <artifactId>jedis</artifactId>
    4. <version>2.9.0</version> //2.9.0才支持cluster密码认证,之前版本的jedisCluster.auth("密码")方法里面什么都没有实现,仅仅抛一个JedisClusterException("No way to dispatch this command to Redis Cluster.")
    5. </dependency>
    1. 整合spring:
    2. <!-- redis集群 -->
    3. <bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">
    4. <constructor-arg index="0">
    5. <set>
    6. <bean class="redis.clients.jedis.HostAndPort">
    7. <constructor-arg index="0" value="${redis.host}"></constructor-arg>
    8. <constructor-arg index="1" value="${redis.port1}"></constructor-arg>
    9. </bean>
    10. <bean class="redis.clients.jedis.HostAndPort">
    11. <constructor-arg index="0" value="${redis.host}"></constructor-arg>
    12. <constructor-arg index="1" value="${redis.port2}"></constructor-arg>
    13. </bean>
    14. <bean class="redis.clients.jedis.HostAndPort">
    15. <constructor-arg index="0" value="${redis.host}"></constructor-arg>
    16. <constructor-arg index="1" value="${redis.port3}"></constructor-arg>
    17. </bean>
    18. <bean class="redis.clients.jedis.HostAndPort">
    19. <constructor-arg index="0" value="${redis.host}"></constructor-arg>
    20. <constructor-arg index="1" value="${redis.port4}"></constructor-arg>
    21. </bean>
    22. <bean class="redis.clients.jedis.HostAndPort">
    23. <constructor-arg index="0" value="${redis.host}"></constructor-arg>
    24. <constructor-arg index="1" value="${redis.port5}"></constructor-arg>
    25. </bean>
    26. <bean class="redis.clients.jedis.HostAndPort">
    27. <constructor-arg index="0" value="${redis.host}"></constructor-arg>
    28. <constructor-arg index="1" value="${redis.port6}"></constructor-arg>
    29. </bean>
    30. </set>
    31. </constructor-arg>
    32. <constructor-arg index="1" value="${redis.timeout}"></constructor-arg>
    33. <constructor-arg index="2" value="${redis.sockettimeout}"></constructor-arg>
    34. <constructor-arg index="3" value="${redis.maxAttempts}"></constructor-arg>
    35. <constructor-arg index="4" value="${redis.pass}"></constructor-arg>
    36. <constructor-arg index="5" ref="jedisPoolConfig"></constructor-arg>
    37. </bean>
    1. @RunWith(SpringJUnit4ClassRunner.class)
    2. @ContextConfiguration("classpath:spring/application*.xml")
    3. public class RedisTest {
    4. @Autowired
    5. private JedisCluster jCluster;
    6. @Test
    7. public void testJCluster() {
    8. jCluster.set("name", "RCL");
    9. String name = jCluster.get("testName");
    10. Assert.assertEquals("RCL", name);
    11. }
     

    转载于:https://www.cnblogs.com/libin6505/p/10704418.html

    展开全文
  • //2.9.0才支持cluster密码认证,之前版本的jedisCluster.auth("密码")方法里面什么都没有实现,仅仅抛一个JedisClusterException("No way to dispatch this command to Redis Cluster.") dependency > 复制代码...
  • springmvc 集成JedisCluster配置

    千次阅读 2020-01-14 20:36:15
    springmvc 集成JedisCluster 配置 点关注不迷路,欢迎再访! 目录springmvc 集成JedisCluster 配置引入依赖配置redis.properties配置redis.xml文件测试验证 cluster相对于哨兵模式是去中心化的,它的每个节点都...
  • JedisCluster连接redis集群(有密码)

    万次阅读 2018-03-16 09:08:00
    redis集群是通过redis-trib.rb方式构建,在连接之前需要导入Jedis包 1.配置文件 #############################...##访问密码 redis.auth = yangfuren ##控制一个pool最多可以有多少个状态为Idle(空)的jedis实例...
  • jedisCluster   非Spring和jedisCluster操作Redis集群 jar包 &lt;!-- 指定版本号 --&gt; &lt;properties&gt; &lt;!-- JEDIS --&gt; &lt;jedis.version&gt;2.7.1&lt;...
  • Redis JedisCluster Spring整合

    千次阅读 2016-10-31 16:44:26
    想用spring直接注入jedisCluster的,但是发现构造函数中的"Set nodes"参数无法配置,在网上找到一个例子,这才知道有FactoryBean这个东西,也算是涨姿势了.原版的网址找不到了,但还是很感谢原作者. 1:spring配置Jedis...
  • 本文搭建redis3.0版本,3.0主要增加了redis cluster集群功能。 1.下载地址:http://download.redis.io/releases/redis-3.0.0.tar.gz,将下载文件拷贝到/usr/local 2.解压源码:tar -zxvf redis-3.0.0.tar....
  • 1、Jedis客户端 https://redis.io/clients 2、Jedis源码包与使用介绍 https://github.com/xetorthio/jedis 3、项目中使用 通过maven引入Jedis的依赖包 <dependency> <groupId>redis.clients<...
  • 修正:这个代码在大数据集群验证测试之后,发现redis连接...1,创建一个工程类,输入集群配置,需要输入密码的哦 package com.dianyou.redis; import org.apache.commons.pool2.PooledObject; import org.apache...
  • Redis随笔(五)Jedis、jedisCluster的使用 1、Jedis客户端 https://redis.io/clients 2、Jedis源码包与使用介绍 https://github.com/xetorthio/jedis 3、项目中使用 通过maven引入Jedis的依赖包 &lt;dependency...
  • Redis集群密码设置 在网上查到一种方式,修改所有Redis集群中的redis.conf文件,加入: masterauth <yourpassword> requirepass <yourpassword> 这种方式需要重新启动各节点,比较麻烦 另一种方式我们...
  • 1、Jedis客户端 https://redis.io/clients 2、Jedis源码包与使用介绍 https://github.com/xetorthio/jedis 3、项目中使用 通过maven引入Jedis的依赖包 <!-- ...
  • 对jedischangyongApi的一些简单封装和分类,全部标有中文注释,可直接放入项目中使用,jedis集群配置可参考 https://blog.csdn.net/qq_31256487/article/details/83144088;
  • JedisCluster API 整理

    2019-03-06 17:36:00
    前提:下面的jedis变量为JedisCluster(redis.clients.jedis.JedisCluster) 1、测试key:value数据 /** * 测试key:value数据 * 集群中flushDB、keys废弃 */ @Test public void testKey() throws ...
  • * Redis(七):JedisCluster 操作API

    千次阅读 2018-03-14 22:59:13
    import org.junit.Test; import redis.clients.jedis.HostAndPort;...import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.Sorti
  • java Jedis api:redis集群api JedisCluster、redis连接池api JedisPool Redis 集群搭建、Spring Data Redis使用 redis 集群搭建 redis报错信息:CLUSTERDOWN Hash slot not served 和 No...
  • 1、通过maven引入Jedis的依赖包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> <type>jar<...
  • Redis随笔Jedis、jedisCluster的使用

    千次阅读 2018-11-26 11:22:58
    1、Jedis客户端 https://redis.io/clients 2、Jedis源码包与使用介绍 https://github.com/xetorthio/jedis 3、项目中使用 通过maven引入Jedis的依赖包 &lt;dependency&gt; &...
  • Redis集群使用JedisCluster并发写数据建立集群连接池 废话不多说,直接上代码. 1.工具类 package com.tjl.util; import redis.clients.jedis.*; import java.util.HashSet; import java.util.Set; /** * @program...
  • // JedisCluster jedisCluster = new JedisCluster(nodes,commandTimeout); //有密码的请使用这一个。 我这里是redis有密码的所以我使用的这一个 return new JedisCluster(nodes,commandTimeout,commandTimeout...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 4,034
精华内容 1,613
关键字:

JedisCluster密码