最近公司项目用户量越来越大,之前的老系统由于设计不合理,已经不能满足目前的需要。现在做了一个新系统,两个系统不同的库,同时在运行。涉及到表id的问题,为了解决这个问题,使用redis来实现分布式id ,具体代码如下:
1,设置一个key实现计数器功能,每取值一次调一次这个方法进行加1操作
public void incr(Integer dbIndex, String key) throws Exception { Jedis jedis = null; try { jedis = jedisPool.getResource(); if (dbIndex != null) { jedis.select(dbIndex); } jedis.incr(key); } finally { // 返还到连接池 if (jedis != null) { jedis.close(); } } }
2,取值
public String get(Integer dbIndex, String key) throws Exception { Jedis jedis = null; try { jedis = jedisPool.getResource(); if (dbIndex != null) { jedis.select(dbIndex); } return jedis.get(key); } finally { // 返还到连接池 if (jedis != null) { jedis.close(); } } }
3,为了避免redis出错所以在取值失败的情况下进行一个随机数处理
public long getId(){ return (long)(Math.random()*900000000 + 100000000); }
完整调用代码:
redisClient.incr(DB,KEY); Long id = Long.parseLong(redisClient.get(DB,KEY)); if (null == id){ id = getId(); }