Commit b5d25191 authored by 李健华's avatar 李健华

添加用户时生成id添加

parent bab6d0a4
package cn.quantgroup.xyqb; package cn.quantgroup.xyqb;
import cn.quantgroup.xyqb.config.SequencerProperties;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.EnableAspectJAutoProxy;
...@@ -25,6 +27,7 @@ import cn.quantgroup.tech.db.EnableDynamicDataSource; ...@@ -25,6 +27,7 @@ import cn.quantgroup.tech.db.EnableDynamicDataSource;
@EnableAspectJAutoProxy @EnableAspectJAutoProxy
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDynamicDataSource @EnableDynamicDataSource
@EnableConfigurationProperties({SequencerProperties.class})
public class Bootstrap { public class Bootstrap {
public static void main(String[] args) { public static void main(String[] args) {
......
package cn.quantgroup.xyqb.config;
import cn.quantgroup.xyqb.util.DefaultSequencer;
import cn.quantgroup.xyqb.util.IdentitySequencer;
import cn.quantgroup.xyqb.util.ServerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* Created by hechao on 2020/1/22.
*/
@Configuration
@EnableConfigurationProperties
public class AutoConfiguration {
@Autowired
private Environment environment;
@EnableConfigurationProperties
class Sequencer {
@Bean
@ConditionalOnMissingBean
public IdentitySequencer identitySequencer(SequencerProperties sequencerProperties) throws Exception {
Integer integerPort = ServerUtils.getIntegerPort(environment);
Long workId = null;
if (integerPort != null) {
workId = integerPort.longValue();
}
if (workId == null) {
throw new IllegalArgumentException("server port is null.");
}
workId = ServerUtils.getLongHostAddress() ^ integerPort;
return new DefaultSequencer(workId, sequencerProperties);
}
}
}
\ No newline at end of file
package cn.quantgroup.xyqb.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Created by hechao on 2020/1/22.
*/
@ConfigurationProperties(prefix = "cn.quantgroup.sequencer")
public class SequencerProperties {
private String operator = "TWEPOCH_XOR";
private Integer sequenceBits = 8;
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public Integer getSequenceBits() {
return sequenceBits;
}
public void setSequenceBits(Integer sequenceBits) {
this.sequenceBits = sequenceBits;
}
@Override
public String toString() {
return "SnowflakepProperties{" +
", sequenceBits=" + sequenceBits +
'}';
}
}
...@@ -42,11 +42,11 @@ public class OauthClientDetailsController { ...@@ -42,11 +42,11 @@ public class OauthClientDetailsController {
} }
@PostMapping("/addLoginInfo") @PostMapping("/addLoginInfo")
public JsonResult addLoginInfo(Long clientId, String phoneNo) { public JsonResult addLoginInfo(Long tenantId, String phoneNo) {
User user = new User(); User user = new User();
user.setPhoneNo(phoneNo); user.setPhoneNo(phoneNo);
user.setId(new Long("111111")); user.setId(new Long("111111"));
oauthLoginInfoService.addLoginInfo(user, clientId); oauthLoginInfoService.addLoginInfo(user, tenantId);
return JsonResult.buildSuccessResultGeneric("12"); return JsonResult.buildSuccessResultGeneric("12");
} }
......
...@@ -40,7 +40,7 @@ public class CustomerLoginEntity extends PartitionEntity implements Serializable ...@@ -40,7 +40,7 @@ public class CustomerLoginEntity extends PartitionEntity implements Serializable
private long customerId; private long customerId;
@Column(name = "UUID", nullable = true) @Column(name = "UUID", nullable = true)
private String uuid; private Long uuid;
public String getInstitutionId() { public String getInstitutionId() {
return institutionId; return institutionId;
...@@ -66,11 +66,11 @@ public class CustomerLoginEntity extends PartitionEntity implements Serializable ...@@ -66,11 +66,11 @@ public class CustomerLoginEntity extends PartitionEntity implements Serializable
this.customerId = customerId; this.customerId = customerId;
} }
public String getUuid() { public Long getUuid() {
return uuid; return uuid;
} }
public void setUuid(String uuid) { public void setUuid(Long uuid) {
this.uuid = uuid; this.uuid = uuid;
} }
......
...@@ -9,5 +9,5 @@ import org.springframework.transaction.annotation.Transactional; ...@@ -9,5 +9,5 @@ import org.springframework.transaction.annotation.Transactional;
* Created by Li Jianhua on 2017/1/3. * Created by Li Jianhua on 2017/1/3.
*/ */
public interface IOauthLoginInfoService { public interface IOauthLoginInfoService {
void addLoginInfo(User user, Long clientId); void addLoginInfo(User user, Long tenantId);
} }
...@@ -7,6 +7,9 @@ import cn.quantgroup.xyqb.repository.IOauthClientDetailsRepository; ...@@ -7,6 +7,9 @@ import cn.quantgroup.xyqb.repository.IOauthClientDetailsRepository;
import cn.quantgroup.xyqb.repository.IProductLoginRepository; import cn.quantgroup.xyqb.repository.IProductLoginRepository;
import cn.quantgroup.xyqb.service.user.IOauthClientDetailsService; import cn.quantgroup.xyqb.service.user.IOauthClientDetailsService;
import cn.quantgroup.xyqb.service.user.IOauthLoginInfoService; import cn.quantgroup.xyqb.service.user.IOauthLoginInfoService;
import cn.quantgroup.xyqb.util.AtomicSequencer;
import cn.quantgroup.xyqb.util.RandomSequencer;
import com.sun.media.sound.AutoConnectSequencer;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -36,27 +39,30 @@ public class OauthLoginInfoServiceImpl implements IOauthLoginInfoService { ...@@ -36,27 +39,30 @@ public class OauthLoginInfoServiceImpl implements IOauthLoginInfoService {
@Autowired @Autowired
private ICustomerLoginRepository customerLoginRepository; private ICustomerLoginRepository customerLoginRepository;
@Autowired
private AtomicSequencer atomicSequencer;
@Override @Override
@Transactional(propagation = Propagation.REQUIRES_NEW) @Transactional(propagation = Propagation.REQUIRES_NEW)
public void addLoginInfo(User user, Long clientId) { public void addLoginInfo(User user, Long tenantId) {
OauthClientDetailsEntity oauthClientDetailsEntity = oauthClientDetailsRepository.findFirstByClientId(clientId); System.out.println(atomicSequencer.nextId());
OauthClientDetailsEntity oauthClientDetailsEntity = oauthClientDetailsRepository.findFirstByClientId(tenantId);
String institutionId = oauthClientDetailsEntity.getInstitutionId(); String institutionId = oauthClientDetailsEntity.getInstitutionId();
String productId = oauthClientDetailsEntity.getProductId(); String productId = oauthClientDetailsEntity.getProductId();
String phoneNo = user.getPhoneNo(); String phoneNo = user.getPhoneNo();
Long userId = user.getId(); Long userId = user.getId();
ProductLoginEntity productLoginEntity = productLoginRepository.findFirstByInstitutionIdAndProductIdAndPhoneNo(institutionId, productId, phoneNo); ProductLoginEntity productLoginEntity = productLoginRepository.findFirstByInstitutionIdAndProductIdAndPhoneNo(institutionId, productId, phoneNo);
String uuid = ""; long uuid = 0L;
// 如果找不到该用户就创建 // 如果找不到该用户就创建
if ("".equals(productLoginEntity) || productLoginEntity == null) { if ("".equals(productLoginEntity) || productLoginEntity == null) {
// 添加用户到产品登录表 // 添加用户到产品登录表
long customerId = 12321321; long customerId = atomicSequencer.nextId();
// long id = session.nextId(); // long id = session.nextId();
long id = 1212; long id = atomicSequencer.nextId();
String customerName = customerId + ""; String customerName = customerId + "";
uuid = UUID.randomUUID().toString(); uuid = RandomSequencer.randomUUID(customerId);
ProductLoginEntity entity = new ProductLoginEntity(); ProductLoginEntity entity = new ProductLoginEntity();
// Integer partitionKey = session.partitionKey(customerId); Integer partitionKey = atomicSequencer.partitionKey(customerId);
Integer partitionKey = 2;
productLoginEntity = EntityBuilder.productLogin(productId, institutionId, phoneNo, customerId, customerName, partitionKey, id); productLoginEntity = EntityBuilder.productLogin(productId, institutionId, phoneNo, customerId, customerName, partitionKey, id);
productLoginEntity.setExtensionAccountId(userId); productLoginEntity.setExtensionAccountId(userId);
productLoginRepository.save(productLoginEntity); productLoginRepository.save(productLoginEntity);
...@@ -68,7 +74,7 @@ public class OauthLoginInfoServiceImpl implements IOauthLoginInfoService { ...@@ -68,7 +74,7 @@ public class OauthLoginInfoServiceImpl implements IOauthLoginInfoService {
// 添加用户到登录表 // 添加用户到登录表
CustomerLoginEntity customerLogin = new CustomerLoginEntity(); CustomerLoginEntity customerLogin = new CustomerLoginEntity();
customerLogin.setId(12312312); customerLogin.setId(atomicSequencer.nextId());
customerLogin.setInstitutionId(institutionId); customerLogin.setInstitutionId(institutionId);
customerLogin.setProductId(productId); customerLogin.setProductId(productId);
customerLogin.setCustomerId(customerId); customerLogin.setCustomerId(customerId);
...@@ -82,7 +88,7 @@ public class OauthLoginInfoServiceImpl implements IOauthLoginInfoService { ...@@ -82,7 +88,7 @@ public class OauthLoginInfoServiceImpl implements IOauthLoginInfoService {
// 添加用户信息表 // 添加用户信息表
CustomerInfoEntity customerInfo = new CustomerInfoEntity(); CustomerInfoEntity customerInfo = new CustomerInfoEntity();
customerInfo.setId(1231111111); customerInfo.setId(atomicSequencer.nextId());
customerInfo.setCustomerId(customerId); customerInfo.setCustomerId(customerId);
customerInfo.setInstitutionId(institutionId); customerInfo.setInstitutionId(institutionId);
customerInfo.setProductId(productId); customerInfo.setProductId(productId);
......
package cn.quantgroup.xyqb.util;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author hechao
* @description
* @date 2020/7/24 13:45
* @modify 2020/7/24 13:45 by hechao
*/
@Component
public class AtomicSequencer {
private final AtomicLong INDEX = new AtomicLong(1L);
private IdentitySequencer sequencer;
public AtomicSequencer(IdentitySequencer sequencer) {
this.sequencer = sequencer;
}
public IdentitySequencer sequencer() {
return sequencer;
}
public long nextId() {
return nextId(INDEX.addAndGet(1L));
}
public long nextId(long position) {
return sequencer.nextId(Math.max(position % 225L, 1L));
}
public long workerId() {
return sequencer.workerId();
}
public long index() {
return INDEX.get();
}
public static long extractPosition(long id) {
return ((id >> 8 << 8) ^ id);
}
public int partitionKey(long id) {
return (int) ((id >> 8 << 8) ^ id);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Sequencer{")
.append("INDEX = ").append(index())
.append(",sequencer = ").append(sequencer)
.append("}");
return sb.toString();
}
}
\ No newline at end of file
package cn.quantgroup.xyqb.util;
import cn.quantgroup.xyqb.config.SequencerProperties;
/**
* Created by hechao on 2020/2/3.
*/
public class DefaultSequencer extends SnowflakeIdentitySequencer {
public DefaultSequencer(long workerId, SequencerProperties properties) {
this(workerId, properties.getSequenceBits(), properties.getOperator());
}
public DefaultSequencer(long workerId, int sequenceBits, String oper) {
super(workerId, sequenceBits, oper);
}
public DefaultSequencer(long workerId, int sequenceBits) {
super(workerId, sequenceBits);
}
public DefaultSequencer(long workerId) {
super(workerId);
}
}
package cn.quantgroup.xyqb.util;
/**
* Created by hechao on 2017/8/28.
*/
public interface IdentitySequencer {
/**
* 得到下一个唯一ID
* @return
*/
long nextId();
/**
* 得到下一个唯一ID
* @param flake 片值
* @return
*/
long nextId(long flake);
/**
* 得到节点ID
* @return
*/
long workerId();
}
\ No newline at end of file
package cn.quantgroup.xyqb.util;
import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.UUID;
/**
* Created by hechao on 2020/2/13.
*/
public abstract class RandomSequencer {
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final SecureRandom RANDOM = new SecureRandom();
public static String randomNumber() {
char[] chars = new char[32];
for (int index = 0; index < chars.length; ++index) {
chars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(chars);
}
public static int next() {
return next(3, 0, 0);
}
public static int next(int size, int zeros) {
return next(size, zeros, 0);
}
public static int next(int size, int zeros, int minimum) {
int s = (int) (System.nanoTime() % (int) Math.pow(10, size));
return Math.max(s - (s % (int) Math.pow(10, zeros)), minimum);
}
public static long randomUUID(Long id) {
UUID uuid = UUID.randomUUID();
String most = Long.toHexString(uuid.getMostSignificantBits());
String least = Long.toHexString(uuid.getLeastSignificantBits());
return id ^ Long.parseLong(most.substring(0, 8), 16) * 31L
^ Long.parseLong(least.substring(0, 4), 16) * 31L
^ Long.parseLong(most.substring(8, 12), 16) * 31L
^ Long.parseLong(least.substring(4), 16) * 31L
^ Long.parseLong(most.substring(12), 16) * 31L;
}
//number
public static String hexUUID(Long id) {
// return Long.toHexString(id) + Long.toHexString(UUID.randomUUID().getMostSignificantBits());
Long uuid = randomUUID(id);
return new StringBuilder().append(Long.toHexString(id & 0xFFFFFFFFL)).append(Long.toHexString(uuid)).append(Long.toHexString(id >> 32)).toString();
}
public static String decUUID(Long id) {
LocalDate date = LocalDate.now();
long time = (long) date.getYear() * 10000L;
time = time + ((long) date.getMonthValue() * 100L);
time = (time + (long) date.getDayOfMonth()) * 100000L + (long) LocalTime.now().toSecondOfDay();
return new StringBuilder().append(time).append(randomUUID(id)).toString();
}
public static void main(String[] args) {
long id = 255255255255L ^ 8000L;
SnowflakeIdentitySequencer snowflakeIdWorker = new SnowflakeIdentitySequencer(id, 8);
String decUUID = RandomSequencer.decUUID(snowflakeIdWorker.nextId());
System.out.println(decUUID);
System.out.println(RandomSequencer.next(3, 0));
}
}
\ No newline at end of file
package cn.quantgroup.xyqb.util;
import org.springframework.core.env.Environment;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;
/**
* Created by hechao on 2020/1/21.
*/
public abstract class ServerUtils {
public static Set<ObjectName> getMBeanSet(String name, String attr, String value) throws MalformedObjectNameException {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> names = beanServer.queryNames(new ObjectName(name)
, Query.match(Query.attr(attr), Query.value(value)));
return names;
}
public static String getHostAddress() throws UnknownHostException {
return InetAddress.getLocalHost().getHostAddress();
}
public static String getPort(Environment environment) throws MalformedObjectNameException {
Set<ObjectName> mBeanSet = getMBeanSet("*:type=Connector,port=*", "scheme", "domain");
String port = null;
if (mBeanSet.size() > 0) {
port = mBeanSet.iterator().next().getKeyProperty("port");
}
if (port == null) {
port = environment.getProperty("server.port");
}
return port;
}
public static Long getLongHostAddress(String address) throws UnknownHostException {
String[] ip = address.split("\\.");
return (Long.parseLong(ip[0]) << 24) + (Long.parseLong(ip[1]) << 16) + (Long.parseLong(ip[2]) << 8) + Long.parseLong(ip[3]);
}
public static Long getLongHostAddress() throws UnknownHostException {
return getLongHostAddress(getHostAddress());
}
public static Integer getIntegerPort(Environment environment) throws MalformedObjectNameException {
String port = getPort(environment);
return port == null || port.equals("") ? null : Integer.valueOf(port);
}
public static Integer getIntegerPort() throws MalformedObjectNameException {
return getIntegerPort(null);
}
public static void main(String[] args) {
try {
System.out.println(ServerUtils.getLongHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
package cn.quantgroup.xyqb.util;
/**
* Created by hechao on 2017/8/28.
*/
public class SnowflakeIdentitySequencer implements IdentitySequencer {
private static final long MAX_WORKER_ID = 0xFFFFFFFFFFL;
private final static int bits = 63;
private final static int SEQ_MAX_BITS = 8;
private final static int SEQ_MIN_BITS = 2;
private final static int timestampMinBits = 41;
private final static int FLAKE_BITS = 8;
private final long twepoch;
private final static long START_DATE = 473356800000L;
private final int sequenceBits;
private volatile long lastTimestamp = -1L;
private volatile long timestamp = -1L;
private volatile long sequence = 0L;
private final long sequenceMask;
private final long workerId;
public final static String TWEPOCH_XOR = "TWEPOCH_XOR";
public final static String TWEPOCH_PLUS = "TWEPOCH_PLUS";
public SnowflakeIdentitySequencer(long workerId, int sequenceBits, String oper) {
if (workerId > MAX_WORKER_ID || workerId < 1) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", MAX_WORKER_ID, 1));
}
if (sequenceBits > SEQ_MAX_BITS || sequenceBits < 2) {
throw new IllegalArgumentException(String.format("sequence bits can't be greater than %d or less than 0", SEQ_MAX_BITS, 2));
}
this.workerId = workerId;
if (TWEPOCH_XOR.equals(oper)) {
this.twepoch = START_DATE ^ workerId;
} else if (TWEPOCH_PLUS.equals(oper)) {
this.twepoch = START_DATE + workerId;
} else {
throw new IllegalArgumentException("operator use TWEPOCH_XOR or TWEPOCH_PLUS");
}
this.sequenceBits = sequenceBits;
this.sequenceMask = -1 << sequenceBits ^ -1;
}
public SnowflakeIdentitySequencer(long workerId, int sequenceBits) {
this(workerId, sequenceBits, TWEPOCH_XOR);
}
public SnowflakeIdentitySequencer(long workerId) {
this(workerId, SEQ_MAX_BITS);
}
public synchronized long nextId(long flake) {
timestamp = System.currentTimeMillis();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
while (timestamp == lastTimestamp) {
timestamp = System.currentTimeMillis();
}
}
}
lastTimestamp = timestamp;
return ((((timestamp - twepoch) << sequenceBits) | sequence) << FLAKE_BITS) | flake;
// return ((timestamp - twepoch) << sequenceBits) | sequence;
}
public long nextId() {
return nextId(0L);
}
@Override
public long workerId() {
return workerId;
}
@Override
public String toString() {
return "SnowflakeIdWorker{" +
"sequence=" + sequence +
", twepoch=" + twepoch +
", workerId=" + workerId +
'}';
}
public static void main(String[] args) {
SnowflakeIdentitySequencer snowflakeIdWorker = new SnowflakeIdentitySequencer(255255255255L ^ 8000, 8);
// SnowflakeIdentitySequencer snowflakeIdWorker = new SnowflakeIdentitySequencer(1099511627775L, 8, TWEPOCH_PLUS);
// SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(255255255255L, 16, 8);
// SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(255255255255L, 16, 8);
// SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(17202801560208L);
Long nextId = snowflakeIdWorker.nextId(245);
System.out.println(nextId);
// for(int i=0; i<300;i++){
// System.out.println(i+":"+(i&255));
// }
// for (int i = 0; i < 100; i++) {
// new Thread(new Running(snowflakeIdWorker)).start();
// }
// System.out.println(73361139375145112L ^ (73361139375145112L >> 8 << 8));
// System.out.println((nextId >> 8 << 8) ^ nextId);
// for (int i = 0; i < 10000; i++) {
// System.out.println(snowflakeIdWorker.nextId());
// }
}
public static class Running implements Runnable {
SnowflakeIdentitySequencer sequencer;
public Running(SnowflakeIdentitySequencer sequencer) {
this.sequencer = sequencer;
}
@Override
public void run() {
System.out.println(this.sequencer.nextId(255));
}
}
}
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment