Springboot專案,多執行緒測試使用Redis生成訂單id
阿新 • • 發佈:2019-01-04
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上結果:
程式碼寫在這裡,如果有看官看到並發現錯誤,歡迎指正,謝謝!
第一次寫部落格,請各位看官們見諒~~