Java分布式锁

来源:互联网 发布:51网络技术论坛 编辑:程序博客网 时间:2024/06/11 22:33

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);        }    }



原创粉丝点击