pom文件添加Redisson依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.6.5</version>
</dependency>
application配置redis信息:我的redis没有设置密码,你们有的可以加一个password填上自己的密码
spring:
redis:
host: localhost
port: 6379
timeout: 1000
写一个Redisson配置类生成bean:
package com.hengtong.led.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 RedissonClientConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private String port;
@Bean
public RedissonClient getRedisson(){
Config config = new Config();
config.useSingleServer().setAddress("redis://" + host + ":" + port);
return Redisson.create(config);
}
}
我写了个RedisLockUtils类来封装加锁操作,里面写了一个lock加锁方法,还有testThreadLock生成100个线程模拟高并发抢锁情况:
package com.hengtong.led.utils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisLockUtils {
@Autowired
private RedissonClient redisson;
public void lock(String key, String num){
RLock lock = redisson.getLock(key);
boolean locked = false;
try{
locked = lock.tryLock(10, TimeUnit.SECONDS);
if (locked){
//开始写业务
System.out.println(num + "锁住了。。。");
System.out.println(num + "模拟业务耗时开始。。");
Thread.sleep(10);
System.out.println(num + "模拟业务耗时结束。。。");
} else {
System.out.println(num + "没锁住。。。");
}
}catch (Exception e){
e.printStackTrace();
} finally {
if (locked){
System.out.println(num + "释放锁");
System.out.println();
lock.unlock();
}
}
}
public void testThreadLock(){
String key = "threadLock";
for (int i=1; i<100; i++){
new Thread(){
@Override
public void run(){
lock("test", this.getName());
}
}.start();
}
}
}
写个测试方法TestRedissonLock测试下在100线程同时争抢的情况下,有没有成功锁住
package com.hengtong.led;
import com.hengtong.led.utils.RedisLockUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestRedissonLock {
@Autowired
private RedisLockUtils redisLockUtils;
@Test
public void testLock(){
redisLockUtils.testThreadLock();
}
}
运行测试方法;控制台打印结果如下:
可以看到,同一时刻只允许一个线程拥有锁,当一个线程抢到锁时,其他线程只能等待线程释放锁。
好了,祝你生活愉快,觉得有用劳烦点个赞评个论谢谢!!
来源:CSDN
作者:头发与代码并存
链接:https://blog.csdn.net/k15014428090/article/details/90671287