1.依赖引入
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.8.2</version>
</dependency>
2.获取RedisClient
package com.example.demo.lock;
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;
@Configuration
public class LockDataConfig {
@Bean
public RedissonClient getClient() {
Config config = new Config();
config.useSingleServer().setAddress("redis://ip:port").setDatabase(15).setPassword("123456");
RedissonClient redissonClient = Redisson.create(config);
return redissonClient;
}
}
2.应用实例
2.1–体现锁机制此处利用ThreadPoolExecutor创建多线程方式调用
package com.example.demo.lock.executor;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程池工具类
*/
public class ThreadExecutor {
/**
参数:核心线程数/最大线程数/空闲线程生存时间/生存时间单位/阻塞队列/拒绝策略
* 拒绝策略:
* (1)AbortPolicy
ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
(2)DiscardPolicy
ThreadPoolExecutor.DiscardPolicy:丢弃任务,但是不抛出异常。如果线程队列已满,则后续提交 的任务都会被丢弃,且是静默丢弃。
使用此策略,可能会使我们无法发现系统的异常状态。建议是一些无关紧要的业务采用此策略。例如,本人的博客网站统计阅读量就是采用的这种拒绝策略。
(3)DiscardOldestPolicy
ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新提交被拒绝的任务。
此拒绝策略,是一种喜新厌旧的拒绝策略。是否要采用此种拒绝策略,还得根据实际业务是否允许丢弃老任务来认真衡量。
(4)CallerRunsPolicy
ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务.如果任务被拒绝了,则由调用线程(提交任务的线程)直接执行此任务
*/
public static ThreadPoolExecutor createExecutor() {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("test-thread-pool-%d").build();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
16, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
System.out.println("线程核心数" + Runtime.getRuntime().availableProcessors());
return threadPoolExecutor;
}
}
2.2具体应用实例
package com.example.demo.lock.service.impl;
import com.example.demo.lock.executor.ThreadExecutor;
import com.example.demo.lock.service.LockService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Service("lockService")
public class LockServiceImpl implements LockService {
@Autowired
private RedissonClient redissonClient;
int init = 1;
int total = 100;
/**
* 加锁调用方法
*
* @param executor
*/
private void printSthWithLock(ThreadPoolExecutor executor) {
RLock mylock = redissonClient.getLock("mylock");
while (true) {
try {
if (init > total) {
System.out.println(Thread.currentThread().getName() + "++++shutdown");
//线程停止
executor.shutdown();
executor.awaitTermination(0L, TimeUnit.SECONDS);
return;
}
boolean isLock = mylock.tryLock(500, 300, TimeUnit.MILLISECONDS);
if (isLock) {
if (init <= total) {
//模拟网络阻塞
Thread.sleep(200);
System.out.println(Thread.currentThread().getName() + "++++" + init);
init++;
}
}
} catch (Exception e) {
} finally {
//释放锁
mylock.unlock();
}
}
}
/**
* 不加锁调用方法
*
* @param executor
* @throws InterruptedException
*/
private void printSthWithoutLock(ThreadPoolExecutor executor) throws InterruptedException {
while (true) {
if (init <= total) {
System.out.println(Thread.currentThread().getName() + "++++++" + init);
Thread.sleep(300);
init++;
} else {
System.out.println("结束");
executor.shutdown();
executor.awaitTermination(0L, TimeUnit.SECONDS);
}
}
}
@Override
public void exceutor() {
ThreadPoolExecutor executor = ThreadExecutor.createExecutor();
init = 1;
//模拟多线程调用
for (int i = 0; i < 200; i++) {
executor.execute(() -> {
try {
printSthWithLock(executor);
} catch (Exception e) {
}
});
}
}
}
3.编写controller方便postMan测试
package com.example.demo.lock.controller;
import com.example.demo.lock.service.LockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/lock")
public class LockController {
@Autowired
private LockService lockService;
@RequestMapping("/redisson")
public String redissonLock() {
lockService.exceutor();
return "1";
}
}