Redisson 的簡單使用(springBoot項目)
maven:
<!-- redisson 分佈式鎖-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.17.7</version>
</dependency>
redis yml配置
spring:
redis:
host: 127.0.0.1
port: 6379
如果有父級項目,可在父級項目寫好以下配置類,自定義註解(單項目可直接用配置類、初始類即可):
配置類
package com.gingersoft.common.redisson;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
*
* @author xss
* @version 1.0.0
* @date 2022-11-22 17:00
*/
@Data
@ConfigurationProperties(prefix = "spring.redis")
public class RedissonConfig {
/**
* redis 地址
*/
private String host;
/**
* 端口
*/
private String port;
/**
* 密碼
*/
private String password;
}
初始化配置類
package com.gingersoft.common.redisson;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author xss
* @version 1.0.0
* @date 2022-11-22 17:00
*/
@Data
@Configuration
@SuppressWarnings("all")
public class RedissonInit {
@Bean
public RedissonConfig RedissonInit() {
return new RedissonConfig();
}
/**
* 創建客戶端
*
* @param redissonConfig redis 配置
* @return 客戶端
*/
@Bean
public RedissonClient redissonClient(RedissonConfig redissonConfig) {
// 配置類
Config config = new Config();
// 添加redis地址
config.useSingleServer().setAddress("redis://" + redissonConfig.getHost() + ":" + redissonConfig.getPort());
// 添加redis密碼
config.useSingleServer().setPassword(StringUtils.isEmpty(redissonConfig.getPassword()) ? null : redissonConfig.getPassword());
//線程池數量 默认值: 当前处理核数量 * 2 这个线程池数量被所有RTopic对象监听器,RRemoteService调用者和RExecutorService任务共同共享
// config.setThreads(2)
//监控锁的看门狗超时,单位:毫秒 默认值:30000
// config.setLockWatchdogTimeout(3000);
return Redisson.create(config);
}
}
自定義註解(如果是寫在父級項目中,在子項目的啟動類加上此註解即可):
package com.gingersoft.common.redisson;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* 分佈式鎖註解
* @author xss
* @version 1.0.0
* @date 2022-11-22 17:00
*/
//保留時間
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
//作用類型
@Target({java.lang.annotation.ElementType.TYPE})
@Documented
@Import(RedissonInit.class)
@Configuration
public @interface EnableRedissonExecutor {
}
子項目啟動類
package com.gingersoft.order;
import com.gingersoft.common.aliyunOss.EnableOssExecutor;
import com.gingersoft.common.db.EnableSessionFactory;
import com.gingersoft.common.redisson.EnableRedissonExecutor;
import com.gingersoft.common.xxljob.EnableXxlJobExecutor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@EnableSessionFactory
@ServletComponentScan
@EnableXxlJobExecutor
@EnableOssExecutor
@EnableFeignClients
//redisson 註解
@EnableRedissonExecutor
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
----------接口簡單使用redisson
redisKey:
package com.gingersoft.order.cache;
/**
* 分佈式鎖 key
* @author xss
* @version 1.0.0
* @date 2022-11-25 17:00
*/
public interface RedisLockKey {
/**
* 套票下單 key
*/
String LOCK_ADD_PACKAGE_ORDER = "LOCK_ADD_PACKAGE_ORDER_";
/**
* 等待時間
*/
long WAITE_TIME_ONE = 1;
/**
* 過期時間
*/
long EXPIRATION_TIME_THREE = 3;
}
接口示例:
@Autowired
private RedissonClient redissonClient;
/**
* 下單
*
* @param params 購買訂單
*/
@PostMapping(value = "/api/cloudGsa/addPackageOrder", produces = APPLICATION_JSON_UTF8_VALUE)
public String addPackageOrder(HttpServletRequest request, @Validated(Insert.class) @RequestBody PackageOrderParams params) {
// 獲取鎖(可重入)
RLock lock = redissonClient.getLock(RedisLockKey.LOCK_ADD_PACKAGE_ORDER + params.getCouponPackageId());
try {
// 分佈式鎖,防止庫存超賣 ,參數1:獲取鎖,拿不到鎖等待1s,參數2:鎖過期時間3s 參數3:單位
if (lock.tryLock(RedisLockKey.WAITE_TIME_ONE, RedisLockKey.EXPIRATION_TIME_THREE, TimeUnit.SECONDS)) {
// 獲得鎖進入
return "獲取鎖,處理業務邏輯";
} else {
// 等待1s仍然拿不到鎖,直接return
return "未獲取鎖,return錯誤信息";
}
} catch (Exception e) {
log.error("/api/cloudGsa/addPackageOrder", e);
return "異常";
} finally {
log.info("线程:" + Thread.currentThread().getName() + "准备释放锁");
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
// 釋放鎖
log.info("线程:" + Thread.currentThread().getName() + "释放锁");
lock.unlock();
}
}
}