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

1 篇文章 0 订阅
1 篇文章 0 订阅

 测试使用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

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值