好家伙,前端出了点bug
我们来搞定后端先:
后端我们用的框架是Spring boot
数据库:MySQl
代码已开源,连接在最后
新建项目:
只点Java Web
项目目录如下:
web服务,mysql连接驱动等一系列包
pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wulaoda</groupId>
<artifactId>loginhouduan</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>loginhouduan</name>
<description>loginhouduan</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 链接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<!-- mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<!-- 实体字段校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml文件:
server:
port: 3312
spring:
datasource:
url: jdbc:mysql://localhost:3306/cruddemo?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
SysUserController.java
定义数据类型
并为其创建相应的getter和setter方法:
然后就是这样:
package com.wulaoda.loginhouduan.entity;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("sys_user")
public class SysUserEntity {
private Long id;
private String LoginName;
private String name;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLoginName() {
return LoginName;
}
public void setLoginName(String loginName) {
LoginName = loginName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "SysUserEntity{" +
"id=" + id +
", LoginName='" + LoginName + '\'' +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
SysUserController.java文件:
package com.wulaoda.loginhouduan.controller;
import com.wulaoda.loginhouduan.req.SysUserLoginReq;
import com.wulaoda.loginhouduan.req.SysUserSaveReq;
import com.wulaoda.loginhouduan.resp.CommonResp;
import com.wulaoda.loginhouduan.resp.SysUserLoginResp;
import com.wulaoda.loginhouduan.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
//绑定数据库表名
@RequestMapping("/sys-user")
public class SysUserController {
@Autowired
private SysUserService sysUserService;
@PostMapping("register")
// zxcv1234
public CommonResp register(@RequestBody SysUserSaveReq req){
req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
CommonResp resp = new CommonResp<>();
sysUserService.register(req);
return resp;
}
@PostMapping("login")
public CommonResp login(@RequestBody SysUserLoginReq req){
// zxcv1234
req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
CommonResp resp = new CommonResp<>();
SysUserLoginResp loginResp = sysUserService.login(req);
resp.setContent(loginResp);
return resp;
}
}
SysUserMapper.java文件:
package com.wulaoda.loginhouduan.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wulaoda.loginhouduan.entity.SysUserEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SysUserMapper extends BaseMapper<SysUserEntity> {
}
SysUserLoginReq.java文件:
package com.wulaoda.loginhouduan.req;
public class SysUserLoginReq {
private String LoginName;
private String password;
public String getLoginName() {
return LoginName;
}
public void setLoginName(String loginName) {
LoginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "SysUserEntity{" +
", LoginName='" + LoginName + '\'' +
", password='" + password + '\'' +
'}';
}
}
SysUserSaveReq.java文件:
package com.wulaoda.loginhouduan.req;
import com.baomidou.mybatisplus.annotation.TableName;
public class SysUserSaveReq {
private Long id;
private String LoginName;
private String name;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLoginName() {
return LoginName;
}
public void setLoginName(String loginName) {
LoginName = loginName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "SysUserEntity{" +
"id=" + id +
", LoginName='" + LoginName + '\'' +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
CommonResp.java文件:
package com.wulaoda.loginhouduan.resp;
public class CommonResp<T> {
// 业务上的成功与失败
private Boolean success = true;
// 返回信息
private String message;
//返回范型数据 自定义类型
private T content;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
@Override
public String toString() {
return "CommonResp{" +
"success=" + success +
", message='" + message + '\'' +
", content=" + content +
'}';
}
}
SysUserLoginResp
package com.wulaoda.loginhouduan.resp;
public class CommonResp<T> {
// 业务上的成功与失败
private Boolean success = true;
// 返回信息
private String message;
//返回范型数据 自定义类型
private T content;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
@Override
public String toString() {
return "CommonResp{" +
"success=" + success +
", message='" + message + '\'' +
", content=" + content +
'}';
}
}
impl/SysUserServicelmpl.java文件:
package com.wulaoda.loginhouduan.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wulaoda.loginhouduan.entity.SysUserEntity;
import com.wulaoda.loginhouduan.mapper.SysUserMapper;
import com.wulaoda.loginhouduan.req.SysUserLoginReq;
import com.wulaoda.loginhouduan.req.SysUserSaveReq;
import com.wulaoda.loginhouduan.resp.SysUserLoginResp;
import com.wulaoda.loginhouduan.service.SysUserService;
import com.wulaoda.loginhouduan.utils.CopyUtil;
import com.wulaoda.loginhouduan.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import java.util.List;
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {
@Resource
private SysUserMapper sysUserMapper;
@Autowired
private SnowFlake snowFlake;
@Override
public void register(SysUserSaveReq req) {
SysUserEntity user = CopyUtil.copy(req, SysUserEntity.class);
if(ObjectUtils.isEmpty(req.getId())){
SysUserEntity userDb = selectByLoginName(req.getLoginName());
if(ObjectUtils.isEmpty(userDb)){
user.setId(snowFlake.nextId());
sysUserMapper.insert(user);
}
}
}
@Override
public SysUserLoginResp login(SysUserLoginReq req) {
SysUserEntity userDb = selectByLoginName(req.getLoginName());
if(ObjectUtils.isEmpty(userDb)){
//用户不存在
return null;
}else {
//登陆成功
SysUserLoginResp userLoginResp = CopyUtil.copy(userDb, SysUserLoginResp.class);
return userLoginResp;
}
}
//查询loginName是否被注册
public SysUserEntity selectByLoginName(String loginName){
QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
wrapper.lambda().eq(SysUserEntity::getLoginName,loginName);
List<SysUserEntity> userEntityList = sysUserMapper.selectList(wrapper);
if(CollectionUtils.isEmpty(userEntityList)){
return null;
}else {
return userEntityList.get(0);
}
}
}
SysUserService.java文件:
package com.wulaoda.loginhouduan.service;
import com.wulaoda.loginhouduan.req.SysUserLoginReq;
import com.wulaoda.loginhouduan.req.SysUserSaveReq;
import com.wulaoda.loginhouduan.resp.SysUserLoginResp;
public interface SysUserService {
void register(SysUserSaveReq req);
SysUserLoginResp login(SysUserLoginReq req);
}
算法优化部分:
CopyUtil.java文件:
package com.wulaoda.loginhouduan.utils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class CopyUtil {
/**
* 单体复制
*/
public static <T> T copy(Object source, Class<T> clazz) {
if (source == null) {
return null;
}
T obj = null;
try {
obj = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BeanUtils.copyProperties(source, obj);
return obj;
}
/**
* 列表复制
*/
public static <T> List<T> copyList(List source, Class<T> clazz) {
List<T> target = new ArrayList<>();
if (!CollectionUtils.isEmpty(source)){
for (Object c: source) {
T obj = copy(c, clazz);
target.add(obj);
}
}
return target;
}
}
SnowFlake.java文件:
package com.wulaoda.loginhouduan.utils;
import org.springframework.stereotype.Component;
import java.text.ParseException;
/**
* Twitter的分布式自增ID雪花算法
**/
@Component
public class SnowFlake {
/**
* 起始的时间戳
*/
private final static long START_STMP = 1609459200000L; // 2021-01-01 00:00:00
/**
* 每一部分占用的位数
*/
private final static long SEQUENCE_BIT = 12; //序列号占用的位数
private final static long MACHINE_BIT = 5; //机器标识占用的位数
private final static long DATACENTER_BIT = 5;//数据中心占用的位数
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId = 1; //数据中心
private long machineId = 1; //机器标识
private long sequence = 0L; //序列号
private long lastStmp = -1L;//上一次时间戳
public SnowFlake() {
}
public SnowFlake(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
/**
* 产生下一个ID
*
* @return
*/
public synchronized long nextId() {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
//相同毫秒内,序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列数已经达到最大
if (sequence == 0L) {
currStmp = getNextMill();
}
} else {
//不同毫秒内,序列号置为0
sequence = 0L;
}
lastStmp = currStmp;
return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
| datacenterId << DATACENTER_LEFT //数据中心部分
| machineId << MACHINE_LEFT //机器标识部分
| sequence; //序列号部分
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private long getNewstmp() {
return System.currentTimeMillis();
}
public static void main(String[] args) throws ParseException {
// 时间戳
// System.out.println(System.currentTimeMillis());
// System.out.println(new Date().getTime());
//
// String dateTime = "2021-01-01 08:00:00";
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// System.out.println(sdf.parse(dateTime).getTime());
SnowFlake snowFlake = new SnowFlake(1, 1);
long start = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
System.out.println(snowFlake.nextId());
System.out.println(System.currentTimeMillis() - start);
}
}
}
已开源,前端暂时未写好,后端接口部分后面还要再改
https://gitee.com/tang-and-han-dynasties/login-entity.git