一、生成唯一id
package com.wxx.demo.util;
import java.text.SimpleDateFormat;
/**
* @Author : leisure
* @Date : 2019/1/17
*/
public class IdUtiles {
private static String lead = "leisure";
private static int Guid = 100;
/**
* 创建以字符串打头结尾自增的唯一id
* @return
*/
public static synchronized String creatId(){
long l = System.currentTimeMillis();
Guid += 1;
String format = new SimpleDateFormat("yyyy").format(l);
if (Guid > 999){
Guid = 100;
}
String id = lead + format + l + Guid;
return id;
}
}
二、模拟高并发场景
package com.wxx.demo;
import com.wxx.demo.util.IdUtiles;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.CountDownLatch;
@RunWith(SpringRunner.class)
//@SpringBootTest(classes = LeisureWebApplication.class)
public class TaskTest {
@Test
public void taskTest(){
Runnable task = new Runnable() {
int count = 0;
@Override
public void run() {
count ++;
String id = IdUtiles.creatId();
System.out.println(count);
System.out.println(id);
System.out.println("Thread : " + Thread.currentThread().getId());
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
double executeTime = this.executeTime(100, task);
System.out.println("执行时间: " + executeTime);
}
private double executeTime(int taskCount,Runnable task){
CountDownLatch start = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(taskCount);
for (int i = 0; i < taskCount ; i++) {
Thread thread = new Thread() {
public void run(){
try {
start.await();
try {
task.run();
}finally {
end.countDown();
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
thread.start();
}
long startTime = System.nanoTime();
//开启开关
start.countDown();
long endTime = System.nanoTime();
return endTime - startTime;
}
}
public class Guid {
public static String getGuid(){
int machineId = 1;//最大支持1-9个集群机器部署
int hashCodev = UUID.randomUUID().toString().hashCode();
System.out.println(UUID.randomUUID().toString());
if(hashCodev < 0){
//有可能是负数
hashCodev = -hashCodev;
}
//"%015d"的意思:0代表不足位数的补0,这样可以确保相同的位数,15是位数也就是要得到到的字符串长度是15,d代表数字。
return machineId + String.format("%015d", hashCodev);
}