Java分布式锁

1、分布式锁需求广泛存在于分布式应用



三种方案的比较
从理解的难易程度角度(从低到高)
数据库 > 缓存 > Zookeeper

从实现的复杂性角度(从低到高)
Zookeeper >= 缓存 > 数据库

从性能角度(从高到低)
缓存 > Zookeeper >= 数据库

从可靠性角度(从高到低)
Zookeeper > 缓存 > 数据库


2、借助Redis中SETNX和GETSET实现分布式锁


3、注意:Jedis不是线程安全的,应该避免直接创建多个Jedis实例,要保证线程安全且获得较好的性能,可以使用JedisPool

创建JedisPool代码示例

private static Map<String, JedisPool> pools = new HashMap<String, JedisPool>();

   public static synchronized JedisPool getPool(String id)
    {
        if (id == null || id.equals(""))
        {
            RedisLog.warn("获取redis连接池时id为空");
            return null;
        }
        String[] temp = id.split(":");
        if (temp.length != 3)
        {
            RedisLog.warn("非法的参数,id=" + id);
            return null;
        }
        if (!pools.containsKey(id))
        {
            RedisLog.info("【" + id + "】连接池不存在,即将创建...");
            JedisPoolConfig config = new JedisPoolConfig();//Jedis池配置
            config.setMinIdle(minIdle);
            config.setMaxIdle(maxIdle);
            config.setMaxTotal(maxTotal);
            config.setMaxWaitMillis(maxWaitMillis);
            config.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
            config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
            config.setTestOnBorrow(true);
            config.setTestOnReturn(true);
            config.setTestWhileIdle(true);
            JedisPool pool = new JedisPool(config, temp[0], Integer.parseInt(temp[1]), timeout, null, Integer.parseInt(temp[2]));
            pools.put(id, pool);
            RedisLog.info("【" + id + "】连接池创建成功" + new Gson().toJson(config));
            return pool;
        }
        else
        {
            return pools.get(id);
        }
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值