spring boot 使用redis 的 incr创建分布式自增id

 测试使用springboot加载类测试,使用本地redis, 模拟多线程去生成规律的自增id

@Component
public class Common implements CommandLineRunner {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void run(String... args) throws Exception {
        long start = System.currentTimeMillis();
        Thread thread1 = new Thread(new Test1());
        Thread thread2 = new Thread(new Test1());
        Thread thread3 = new Thread(new Test1());
        thread1.start();
        thread2.start();
        thread3.start();
        long end = System.currentTimeMillis();
        System.out.println("耗时:"+(end-start));
    }

    class Test1 implements Runnable{

        @Override
        public void run() {
            getId();

        }

    }

    public void getId(){
        synchronized (this) {
            RedisAtomicLong entityIdCounter = null;

            for(int i=0;i<10;i++){
                if(!redisTemplate.hasKey("ceid")){
                    redisTemplate.opsForValue().increment("ceid", 1);
                    System.out.println("test1使用redis缓存保存数据成功");
                    entityIdCounter= new RedisAtomicLong("ceid", redisTemplate.getConnectionFactory());
                    //incr 默认初始值从0开始,
                    //可以设置初始值,
                    entityIdCounter.set(123);
                }
                entityIdCounter=new RedisAtomicLong("ceid", redisTemplate.getConnectionFactory());
                long increment=0;

                increment = entityIdCounter.incrementAndGet();
                if (i == 5) {
                    increment = entityIdCounter.decrementAndGet();
                    System.out.println("test1:失败,返回上个id");
                }else{
                    System.out.println(increment);
                }
            }

        }
    }

}

redis配置在application.properties中

# REDIS
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址 (默认为127.0.0.1)
spring.redis.host=127.0.0.1
# Redis服务器连接端口 (默认为6379)
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=  
# 连接超时时间(毫秒)
spring.redis.timeout=2000ms

 

你可能感兴趣的:(java,redis,自增id)