Redisson使用示例

发布于:2025-07-07 ⋅ 阅读:(15) ⋅ 点赞:(0)

1,引入依赖(百度搜索即可)

2,配置yaml

spring:
  redis:
    ##redis 单机环境配置
    host: 127.0.0.1
    # host: 10.192.33.144
    port: 6379
    # port: 20051
    # password: 123456
    password: ''
    # database: 1
    database: 0
    ssl: false
    ##redis 集群环境配置
    #cluster:
    #  nodes: 127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003
    #  commandTimeout: 5000

redisson:
  config:
    single-server-config:
      address: "redis://${spring.redis.host}:${spring.redis.port}"   

3,创建配置类

package org.springblade.sample.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RedissonConfig {

    @Value("${redisson.config.single-server-config.address}")
    private String redisAddress;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress(redisAddress);
        return Redisson.create(config);
    }
}

 4,使用示例

	@Resource
	private RedissonClient redissonClient;



	//获取初始编码
	private StringBuffer getInitCode(Integer isForeignInput) {
		String prefix = isForeignInput == 0 ? "BT" : "SR";
		String redisKey = CommonConstant.COVID19_ID + "::" + prefix;
		LocalDate now = LocalDate.now();
		String yearStr = String.valueOf(now.getYear()).substring(2);

		// 获取当前编号信息 当前编号
		long currentNumber = getCodeInfo(redisKey, yearStr, isForeignInput);

		// 生成新编号
		return generateCode(yearStr, prefix, currentNumber - 1);
	}

	//生成唯一编码
	private StringBuffer createCode(Integer isForeignInput) {
		String prefix = isForeignInput == 0 ? "BT" : "SR";
		String redisKey = CommonConstant.COVID19_ID + "::" + prefix;
		LocalDate now = LocalDate.now();
		String yearStr = String.valueOf(now.getYear()).substring(2);

		// 获取当前编号信息 当前编号
		long currentNumber = getCodeInfo(redisKey, yearStr, isForeignInput);

		// 生成新编号
		return generateCode(yearStr, prefix, currentNumber);
	}

	// 获取当前编号信息,返回当前编号
	private long getCodeInfo(String redisKey, String currentYear, Integer isForeignInput) {
		if (redisTemplate.hasKey(redisKey)) {
			String code = (String) redisTemplate.opsForValue().get(redisKey);
			String[] parts = code.split(",");

			// 如果年份变化,重置编号
			if (!parts[0].equals(currentYear)) {
				return 0L;
			}

			return Long.parseLong(parts[1]);
		} else {
			// 查询数据库最新数据
			SampleCovid19 sample = baseMapper.selectPageIn(isForeignInput, CommonConstant.CDC_COVID19);

			if (sample == null) {
				return 0L;
			} else {
				String number = sample.getSampleNo().substring(sample.getSampleNo().lastIndexOf("-") + 1);
				return Long.parseLong(number);
			}
		}
	}

	// 生成编号
	private StringBuffer generateCode(String yearStr, String prefix, Long number) {
		StringBuffer code = new StringBuffer();
		code.append(CommonConstant.CDC_COVID19).append("-").append(yearStr).append("-").append(prefix).append("-").append(number + 1);
		return code;
	}

	// 更新Redis中的编号
	private void updateCodeInRedis(Integer isForeignInput, String code) {
		if (StringUtil.isBlank(code)) {
			return;
		}
		String prefix = isForeignInput == 0 ? "BT" : "SR";
		String redisKey = CommonConstant.COVID19_ID + "::" + prefix;
		String[] parts = code.split("-");
		String number = code.substring(code.lastIndexOf("-") + 1);
		redisTemplate.opsForValue().set(redisKey, parts[2] + "," + number);
	}

	//样本插入线程安全
	public String insertSample(SampleCovid19 sample) {
		String prefix = sample.getIsForeignInput() == 0 ? "BT" : "SR";
		String lockKey = CommonConstant.COVID19_CODE_LOCK + prefix;
		RLock lock = redissonClient.getLock(lockKey);
		boolean isLocked = false;
		try {
			isLocked = lock.tryLock(100, 60, TimeUnit.SECONDS);
			if (!isLocked) {
				throw new ServiceException("获取锁超时,请稍后重试");
			}
			String sampleNo = this.createCode(sample.getIsForeignInput()).toString();
			sample.setSampleNo(sampleNo);
			baseMapper.insert(sample);
			this.updateCodeInRedis(sample.getIsForeignInput(), sampleNo);
			log.info("数据添加成功,样本库编号: {}", sampleNo);
			return sampleNo;
		} catch (Exception e) {
			log.error("数据添加失败,样本编号生成已回滚", e);
			throw new ServiceException("数据插入异常,请联系管理员!");
		} finally {
			if (isLocked && lock.isHeldByCurrentThread()) {
				lock.unlock();
			}
		}
	}