b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

redis一致性hash_redis双主集群部署_spring redis cache(2)

电脑杂谈  发布时间:2017-01-25 20:04:29  来源:网络整理
`
public class ShardedRedis {
    public static void main(String[] args){
        GenericObjectPoolConfig config=new GenericObjectPoolConfig();
        config.setMaxTotal(1000);
        config.setMaxIdle(500);

        List<JedisShardInfo> jedisShardInfoList=new ArrayList<JedisShardInfo>();
        JedisShardInfo shardInfo1=new JedisShardInfo("192.168.217.157",6380);
        JedisShardInfo shardInfo2=new JedisShardInfo("192.168.217.157",6381);
        JedisShardInfo shardInfo3=new JedisShardInfo("192.168.217.157",6382);
        jedisShardInfoList.add(shardInfo1);
        jedisShardInfoList.add(shardInfo2);
        jedisShardInfoList.add(shardInfo3);

        ShardedJedisPool pool=new ShardedJedisPool(config,jedisShardInfoList);

        set("user1","a",pool);
        set("user12","a",pool);
        set("user13","a",pool);
        set("usera","a",pool);
        set("userb","a",pool);
    }

    public static void set(String key,String value,ShardedJedisPool pool){
        ShardedJedis shardedJedis=pool.getResource();
        shardedJedis.set(key,value);
        pool.returnResource(shardedJedis);
    }
}

`
2.jedis实现
* Jedis是通过ShardedJedis向redis集群写入的数据,ShardedJedis中的关键方法:<br/>
`
public Sharded(List<S> shards, Hashing algo, Pattern tagPattern) {
    this.algo = algo;
    this.tagPattern = tagPattern;
    initialize(shards);
}

//初始化哈希环
private void initialize(List<S> shards) {
    nodes = new TreeMap<Long, S>();

    for (int i = 0; i != shards.size(); i) {
        final S shardInfo = shards.get(i);
        if (shardInfo.getName() == null)
        for (int n = 0; n < 160 * shardInfo.getWeight(); n) {
            nodes.put(this.algo.hash("SHARD-"  i  "-NODE-"  n),
                shardInfo);
        }
        else
        for (int n = 0; n < 160 * shardInfo.getWeight(); n) {
            nodes.put(
                this.algo.hash(shardInfo.getName()  "*"
                     shardInfo.getWeight()  n), shardInfo);
        }
        resources.put(shardInfo, shardInfo.createResource());
    }
}

//将key,value存储到相应的shard
 public String set(String key, String value) {
    Jedis j = getShard(key);
    return j.set(key, value);
 }

public R getShard(String key) {
    return resources.get(getShardInfo(key));
}

//根据key获取shard
public S getShardInfo(byte[] key) {
    SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
    if (tail.isEmpty()) {
        return nodes.get(nodes.firstKey());
    }
    return tail.get(tail.firstKey());
}
`
* 以上就是jedis中一致性hash的主要代码,当redis单机存储无法满足要求时,可以考虑使用一致性hash构建redis集群。


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-28693-2.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...