微服务大爆发的年代,分布式锁必不可少。比如在处理库存,账户等信息时分布式锁必不可少。不说了 直接上代码。
第一步、首先maven配置
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.6</version>
</dependency>
第二步、配置redis,这里的redis是可以使用集群的,有需要可以研究下
config.useClusterServers().addNodeAddress() 这个
//yml配置,主要是后面那两句
redis:
host: 127.0.0.1
port: 6379
password: 123456
maxIdle: 10
maxTotal: 50
timeout: 6000
minIdle: 2
maxWaitMillis: 15000
redisson:
url: redis://${spring.redis.host}:${spring.redis.port}
password: ${spring.redis.password}
//java bean配置
import com.feng.common.util.password.PasswordUtils;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
/**
* 分布式锁配置类
*/
@Configuration
@ConfigurationProperties(prefix = "spring.redis.redisson")
public class RedissionConfig {
private String url;
private String password;
@Bean
public Redisson redisson() {
Config config = new Config();
if (StringUtils.isEmpty(password)) {
config.useSingleServer().setAddress(url);
} else {
config.useSingleServer().setAddress(url).setPassword(password);
}
return (Redisson) Redisson.create(config);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3、第三步、实现
这个地方高并发下要考虑集群。我单机测试的 TPS 600多
@Autowired
private Redisson redisson;
@RequestMapping("/deductStock")
public void deductStock() {
RLock lock = redisson.getLock("stockLock"); //获取锁
try {
//加锁:redission默认超时时间为30s,每10s续期一次,也可以自己设置时间
lock.lock(10, TimeUnit.SECONDS);
int stock = Integer.parseInt(redisService.get("stock"));
if (stock > 0) {
int realStock = stock - 1;
redisService.set("stock", realStock + "", 0);//jedis.set(key,value)
System.out.println("扣减成功,剩余库存:" + realStock + "");
} else {
System.out.println("库存不足");
}
} finally {
lock.unlock();
}
}