测试类代码:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ForumServiceApp.class})
@Rollback(false)
public class ForumCommentMobileThreadServiceTest {
@Autowired
private ForumCommentMobileService commentService;
@Autowired
private RedisTemplate redisTemplate;
@Before
public void before() {
HystrixHelper.initializeContextIfNeeded("test");
}
@Test
public void testCreateCommentsThreads() throws Throwable{
//Runner数组,相当于并发多少个线程。
TestRunnable[] trs = new TestRunnable [100];
for(int i=0;i<100;i++){
trs[i]=new createCommentsThread();
}
// 执行多线程测试用例的Runner
MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);
// 执行所有线程
mttr.runTestRunnables();
}
// 自定义的线程
private class createCommentsThread extends TestRunnable {
@Override
public void runTest() throws Throwable {
// 测试内容
createComments();
}
}
// 测试方法
public void createComments() throws Exception {
HystrixHelper.initializeContextIfNeeded("test");
//上面这句很关键
CreateCommentRequestDto request = new CreateCommentRequestDto().entId(20010664).commentCreate(
new CommentCreateDto().replyCommentId(0).postId(10004039).content("comment from user 1: good job")
);
UserDetail userDetail = createUserDetail();
CommonCreateResponseDto response = commentService.createCommentMobile(request, userDetail);
}
执行类代码(控制并发):
BoundValueOperations<String,String> RedisLockOps = redisTemplate.boundValueOps(redisLock);
BoundValueOperations<String,String> RedisOps = redisTemplate.boundValueOps(redisKey);
Integer MaxFloor = 0;
while(!redisTemplate.hasKey(redisKey)){
//没有初始值时
if(RedisLockOps.setIfAbsent("find in mysql")){
//只允许第一条线程进入
RedisLockOps.expire(3, TimeUnit.MINUTES);
MaxFloor = commentRepository.findMaxFloorAndLock(request.getEntId(), createDto.getPostId());
if (MaxFloor == null){
MaxFloor = 0;
}
RedisOps.set(MaxFloor.toString());
RedisOps.expire(3, TimeUnit.HOURS);
break;
}
try {
Thread.sleep(100);
}catch (Exception e){
}
}
MaxFloor = RedisOps.increment(1).intValue();
//拿到后加一
RedisOps.expire(3, TimeUnit.HOURS);
comment.setFloor(MaxFloor);
Long findMaxFloorAndLocke = new Date().getTime();
System.out.println("findMaxFloorAndLock :" + (findMaxFloorAndLocke - findMaxFloorAndLocks));
// if (maxFloor == null) {
// maxFloor = 0;
// }
// comment.setFloor(maxFloor + 1);
commentRepository.save(comment);
关键方法:
BoundXXXOperation.setIfAbsent("value");
BoundXXXOperation.increment("value");