Springboot项目,多线程测试使用Redis生成订单id
springboot测试类:
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
* @date 2018/12/5
* @since 1.0.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
//@WebAppConfiguration
public class BaseApplicationTests {
@Before
public void init() {
System.out.println("begin the test ...........");
}
@After
public void after() {
System.out.println("end the test ...........");
}
}
Redis并使用多线程测试
springboot项目中的redis的配置这里就不在贴上去了。
看测试代码吧:
import org.apache.commons.lang3.time.DateFormatUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* redis生成订单号
*
* @date 2018/12/5
* @since 1.0.0
*/
public class RedisTest extends BaseApplicationTests {
private static String REDIS_MANAGE_CONTRACT_PREFIX = "yuy:manage:TEST_CONTRACT_INC_";
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private Executor executor;
public String generateContractNo() {
//合同编号规则: BNF + 当前日期 + 四位编号,编号每天从1开始递增
String currentDate = DateFormatUtils.format(new Date(), "yyyyMMdd");
String key = REDIS_MANAGE_CONTRACT_PREFIX + currentDate;
long count = redisTemplate.opsForValue().increment(key, 1);
if (count == 1) {
redisTemplate.expireAt(key, getTimeout());
}
return String.format("BNF%s-%s", currentDate, String.format("%04d", count));
}
private Date getTimeout() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
return calendar.getTime();
}
@Test
public void test1() {
Runnable task = () -> {
try {
System.out.println(Thread.currentThread().getName()+" 订单号:"+generateContractNo());
Thread.sleep(500);
} catch (Exception e) {
System.out.println("task interrupted: " + e);
e.printStackTrace();
}
};
ExecutorService executorService = Executors.newFixedThreadPool(5);
try {
for (int i = 0; i < 10; i++) {
executorService.execute(task);
}
Thread.sleep(1000);// 当前主线程休眠
} catch (Exception e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
/*for (int i = 0; i < 10; i++) {
executorService.execute(task);
}
try {
executorService.shutdown();
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
System.out.println("awaitTermination interrupted: " + e);
executorService.shutdownNow();
}*/
}
}
pu上结果:
代码写在这里,如果有看官看到并发现错误,欢迎指正,谢谢!
第一次写博客,请各位看官们见谅~~