栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

抢红包小案例一(Redisson分布式锁)

抢红包小案例一(Redisson分布式锁)

一、配置(pom)
 
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            redis.clients
            jedis
            2.1.0
        

        
            org.redisson
            redisson
            2.11.5
        
        
            org.apache.commons
            commons-lang3
            3.7
        
二、配置(yml)
spring:
  redis:
    database: 0
    # Redis服务器地址
    host: 127.0.0.1
    # Redis服务器连接端口
    port: 6379
    ## Redis服务器连接密码(默认为空)
    password:
    # 连接池最大连接数(使用负值表示没有限制)
    jedis:
      pool:
        max-active: 200
        max-idle:  10
        min-idle: 1
        max-wait: -1ms
    timeout: 5s
  devtools:
    restart:
      enabled: false  #设置开启热部署
      additional-paths: src/main/java #重启目录
      exclude: WEB-INF
//    @Bean
//    @ConditionalOnProperty(name="redisson.master-name")
//    RedissonClient redissonSentinel() {
//        Config config = new Config();
//        SentinelServersConfig serverConfig = config.useSentinelServers().addSentinelAddress(redssionProperties.getSentinelAddresses())
//                .setMasterName(redssionProperties.getMasterName())
//                .setTimeout(redssionProperties.getTimeout())
//                .setMasterConnectionPoolSize(redssionProperties.getMasterConnectionPoolSize())
//                .setSlaveConnectionPoolSize(redssionProperties.getSlaveConnectionPoolSize());
//
//        if(StringUtils.isNotBlank(redssionProperties.getPassword())) {
//            serverConfig.setPassword(redssionProperties.getPassword());
//        }
//        return Redisson.create(config);
//    }
    
    @Bean
    @ConditionalOnProperty(name = "redisson.address")
    RedissonClient redissonSingle() {
        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress(redssionProperties.getAddress())
                .setTimeout(redssionProperties.getTimeout())
                .setConnectionPoolSize(redssionProperties.getConnectionPoolSize())
   .setConnectionMinimumIdleSize(redssionProperties.getConnectionMinimumIdleSize());
        if (StringUtils.isNotBlank(redssionProperties.getPassword())) {
            serverConfig.setPassword(redssionProperties.getPassword());
        }
        return Redisson.create(config);
    }
    
    @Bean
    RedisLockUtil redissLockUtil(RedissonClient redissonClient) {
        RedisLockUtil redissLockUtil = new RedisLockUtil();
        redissLockUtil.setRedissonClient(redissonClient);
        return redissLockUtil;
    }
}

2.RedissonProperties

package com.hylink.tencent.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "redisson")
public class RedissonProperties {

    private int timeout = 3000;

    private String address;

    private String password;

    private int connectionPoolSize = 64;

    private int connectionMinimumIdleSize = 10;

    private int slaveConnectionPoolSize = 250;

    private int masterConnectionPoolSize = 250;

    private String[] sentinelAddresses;

    private String masterName;

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public int getSlaveConnectionPoolSize() {
        return slaveConnectionPoolSize;
    }

    public void setSlaveConnectionPoolSize(int slaveConnectionPoolSize) {
        this.slaveConnectionPoolSize = slaveConnectionPoolSize;
    }

    public int getMasterConnectionPoolSize() {
        return masterConnectionPoolSize;
    }

    public void setMasterConnectionPoolSize(int masterConnectionPoolSize) {
        this.masterConnectionPoolSize = masterConnectionPoolSize;
    }

    public String[] getSentinelAddresses() {
        return sentinelAddresses;
    }

    public void setSentinelAddresses(String sentinelAddresses) {
        this.sentinelAddresses = sentinelAddresses.split(",");
    }

    public String getMasterName() {
        return masterName;
    }

    public void setMasterName(String masterName) {
        this.masterName = masterName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getConnectionPoolSize() {
        return connectionPoolSize;
    }

    public void setConnectionPoolSize(int connectionPoolSize) {
        this.connectionPoolSize = connectionPoolSize;
    }

    public int getConnectionMinimumIdleSize() {
        return connectionMinimumIdleSize;
    }

    public void setConnectionMinimumIdleSize(int connectionMinimumIdleSize) {
        this.connectionMinimumIdleSize = connectionMinimumIdleSize;
    }
}

3.RedisLockUtil

package com.hylink.tencent.util;

import org.redisson.api.RLock;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;


public class RedisLockUtil {
    @Autowired
    private static RedissonClient redissonClient;

    public void setRedissonClient(RedissonClient locker) {
        redissonClient = locker;
    }

    
    public static RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    
    public static void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    
    public static void unlock(RLock lock) {
        lock.unlock();
    }

    
    public static RLock lock(String lockKey, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, TimeUnit.SECONDS);
        return lock;
    }

    
    public static RLock lock(String lockKey, TimeUnit unit, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    
    public static boolean tryLock(String lockKey, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    
    public static boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }

    
    public void initCount(String key, int count) {
        RMapCache mapCache = redissonClient.getMapCache("skill");
        mapCache.putIfAbsent(key, count, 3, TimeUnit.DAYS);
    }

    
    public int incr(String key, int delta) {
        RMapCache mapCache = redissonClient.getMapCache("skill");
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return mapCache.addAndGet(key, 1);//加1并获取计算后的值
    }

    
    public int decr(String key, int delta) {
        RMapCache mapCache = redissonClient.getMapCache("skill");
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return mapCache.addAndGet(key, -delta);//加1并获取计算后的值
    }
}

4.DoubleUtil

package com.hylink.tencent.util;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;


public class DoubleUtil implements Serializable {
    private static final long serialVersionUID = -3345205828566485102L;
    // 默认除法运算精度
    private static final Integer DEF_DIV_SCALE = 2;

    
    public static Double add(Double value1, Double value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1));
        BigDecimal b2 = new BigDecimal(Double.toString(value2));
        return b1.add(b2).doublevalue();
    }

    
    public static double sub(Double value1, Double value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1));
        BigDecimal b2 = new BigDecimal(Double.toString(value2));
        return b1.subtract(b2).doublevalue();
    }

    
    public static Double mul(Double value1, Double value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1));
        BigDecimal b2 = new BigDecimal(Double.toString(value2));
        return b1.multiply(b2).doublevalue();
    }

    
    public static Double divide(Double dividend, Double divisor) {
        return divide(dividend, divisor, DEF_DIV_SCALE);
    }

    
    public static Double divide(Double dividend, Double divisor, Integer scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(dividend));
        BigDecimal b2 = new BigDecimal(Double.toString(divisor));
        return b1.divide(b2, scale, RoundingMode.HALF_UP).doublevalue();
    }

    
    public static double round(double value, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(value));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, RoundingMode.HALF_UP).doublevalue();
    }

    public static void main(String[] args) {
        System.out.println(divide((double) 100, (double) 50));
    }
}

5.RedisUtil

package com.hylink.tencent.util;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public final class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    // ================================String=================================
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(buildKey(key), value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(buildKey(key), value, time, TimeUnit.SECONDS);
            } else {
                set(buildKey(key), value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(buildKey(key));
    }

    
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(buildKey(key), time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public long getExpire(String key) {
        return redisTemplate.getExpire(buildKey(key), TimeUnit.SECONDS);
    }

    
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(buildKey(key));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public long increment(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(buildKey(key), delta);
    }

    
    public long decrement(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(buildKey(key), -delta);
    }

    // ================================zSet=================================

    
    public Boolean zAdd(String key, String value, double score) {
        return redisTemplate.opsForZSet().add(key, value, score);
    }

    
    public Double zIncrementScore(String key, String value, double delta) {
        return redisTemplate.opsForZSet().incrementScore(key, value, delta);
    }

    
    public Set zReverseRange(String key, long start, long end) {
        return redisTemplate.opsForZSet().reverseRange(key, start, end);
    }

    
    public Set> zReverseRangeWithScores(String key, long start, long end) {
        return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);
    }

    // ================================Map=================================

    
    public Object hget(String key, String item) {
        try {
            return redisTemplate.opsForHash().get(buildKey(key), item);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    
    public Map hmget(String key) {
        try {
            return redisTemplate.opsForHash().entries(buildKey(key));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    
    public boolean hmset(String key, Map map) {
        try {
            redisTemplate.opsForHash().putAll(buildKey(key), map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    
    public boolean hmset(String key, Map map, long time) {
        try {
            redisTemplate.opsForHash().putAll(buildKey(key), map);
            if (time > 0) {
                expire(buildKey(key), time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(buildKey(key), item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(buildKey(key), item, value);
            if (time > 0) {
                expire(buildKey(key), time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(buildKey(key), item);
    }


    
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(buildKey(key), item);
    }


    
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(buildKey(key), item, by);
    }


    
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(buildKey(key), item, -by);
    }

    private static String buildKey(String key) {
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }
}

 
四、业务代码 
package com.hylink.tencent.controller;

import com.hylink.tencent.util.CommonResult;
import com.hylink.tencent.util.DoubleUtil;
import com.hylink.tencent.util.RedisLockUtil;
import com.hylink.tencent.util.RedisUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.linkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


@RequestMapping(value = "/red-envelope")
@RestController
public class RedEnvelope {
    private final static Logger log = LoggerFactory.getLogger(RedEnvelope.class);

    private static int corePoolSize = Runtime.getRuntime().availableProcessors();
    
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            corePoolSize,
            corePoolSize + 1,
            120,
            TimeUnit.SECONDS,
            new linkedBlockingQueue<>(1000));
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping(value = "/getEnvelope", method = RequestMethod.GET)
    @ApiOperation(value = "抢红包一")
    public CommonResult analysis(String envelopeId) {
        int skillNum = 20;
        final CountDownLatch latch = new CountDownLatch(skillNum);
        //初始化剩余人数,拆红包拦截
        redisUtil.set("restPeople-" + envelopeId, 10);
        //初始化红包金额,单位为分
        redisUtil.set("money-" + envelopeId, 20000);
        //初始化红包数据,抢红包拦截
        redisUtil.set("num-" + envelopeId, 10);

        //模拟20个用户抢10个红包
        for (int i = 1; i <= skillNum; i++) {
            int userId = i;
            Runnable runnable = () -> {
                //抢红包拦截,其实应该分两步,为了演示方便
                long count = redisUtil.decrement("num-" + envelopeId, 1);
                if (count >= 0) {
                    String secKill = startSecKill(envelopeId, userId);
                    Double amount = DoubleUtil.divide(Double.parseDouble(secKill), (double) 100);
                    log.info("用户{}抢红包成功,金额:{}", userId, amount);
                } else {
                    log.info("用户{}抢红包失败", userId);
                }
                latch.countDown();
            };
            executor.execute(runnable);
        }
        return CommonResult.success();
    }

    
    private String startSecKill(String envelopeId, int userId) {
        int money = 0;
        boolean res = false;
        try {
            
            res = RedisLockUtil.tryLock(envelopeId + "", TimeUnit.SECONDS, 3, 10);
            if (res) {
                long restPeople = redisUtil.decrement("restPeople-" + envelopeId, 1);
                
                if (restPeople == 0) {
                    money = Integer.parseInt(redisUtil.get("money-" + envelopeId).toString());
                } else {
                    int restMoney = Integer.parseInt(redisUtil.get("money-" + envelopeId).toString());
                    Random random = new Random();
                    //随机范围:[1,剩余人均金额的两倍]
                    money = random.nextInt((int) (restMoney / (restPeople + 1) * 2 - 1)) + 1;
                }
                redisUtil.decrement("money-" + envelopeId, money);
                //红包记录异步入库
                //异步入账
            } else {
                
                redisUtil.increment("num-" + envelopeId, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            if (res) {
                RedisLockUtil.unlock(envelopeId + "");
            }
        }
        return money + "";
    }
}

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号