(4)创建mapper路径
(5)编写配置文件
server:
port: 8088
spring:
application:
name: user-service
datasource:
url: jdbc:mysql://127.0.0.1:3306/yun6
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
instance-id: e u r e k a . i n s t a n c e . i p − a d d r e s s . {eureka.instance.ip-address}. eureka.instance.ip−address.{server.port}
lease-renewal-interval-in-seconds: 3
lease-expiration-duration-in-seconds: 10
mybatis:
type-aliases-package: com.leyou.item.pojo
(6)创建pojo
(7)添加网关路由
我们修改ly-gateway
,添加路由规则,对ly-user-service
进行路由:
user-service: /user/**
1、数据结构
CREATE TABLE tb_user
(
id
bigint(20) NOT NULL AUTO_INCREMENT,
username
varchar(50) NOT NULL COMMENT ‘用户名’,
password
varchar(32) NOT NULL COMMENT ‘密码,加密存储’,
phone
varchar(20) DEFAULT NULL COMMENT ‘注册手机号’,
created
datetime NOT NULL COMMENT ‘创建时间’,
salt
varchar(32) NOT NULL COMMENT ‘密码加密的salt值’,
PRIMARY KEY (id
),
UNIQUE KEY username
(username
) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COMMENT=‘用户表’;
数据结构比较简单,因为根据用户名查询的频率较高,所以我们给用户名创建了索引
2、基本代码
实体类
注意:为了安全考虑。这里对password和salt添加了注解@JsonIgnore,这样在json序列化时,就不会把password和salt返回。
ly-user-interface添加依赖
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
ly-user
com.leyou.service
1.0.0-SNAPSHOT
4.0.0
ly-user-interface
javax.persistence
persistence-api
1.0
com.fasterxml.jackson.core
jackson-databind
tk.mybatis
mapper-core
1.0.4
package com.leyou.item.pojo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
@Data
@Table(name = “tb_user”)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;// 用户名
@JsonIgnore
private String password;// 密码
private String phone;// 电话
private Date created;// 创建时间
@JsonIgnore
private String salt;// 密码的盐值
}
mapper
public interface UserMapper extends Mapper {
}
Service
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
}
3.数据验证功能
(1)接口说明:
实现用户数据的校验,主要包括对:手机号、用户名的唯一性校验。
接口路径
GET /check/{data}/{type}
参数说明:
| 参数 | 说明 | 是否必须 | 数据类型 | 默认值 |
| — | — | — | — | — |
| data | 要校验的数据 | 是 | String | 无 |
| type | 要校验的数据类型:1,用户名;2,手机; | 否 | Integer | 1 |
返回结果:
返回布尔类型结果:
-
true:可用
-
false:不可用
状态码:
-
200:校验成功
-
400:参数有误
-
500:服务器内部异常
(2)controller
package com.leyou.user.web;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
}
因为有了接口,我们可以不关心页面,所有需要的东西都一清二楚:
-
请求方式:GET
-
请求路径:/check/{param}/{type}
-
请求参数:param,type
-
返回结果:true或false
package com.leyou.user.web;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
/**
-
校验数据是否可用
-
@param data
-
@param type
-
@return
*/
@GetMapping(“/check/{data}/{type}”)
public ResponseEntity checkData(@PathVariable(“data”) String data,
@PathVariable(“type”) Integer type) {
return ResponseEntity.ok(userService.checkData(data,type));
}
}
(3)Service
package com.leyou.user.service;
import com.leyou.item.pojo.User;
import com.leyou.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public Boolean checkData(String data, Integer type) {
User user = new User();
//判断数据类型
switch (type){
case 1:
user.setUsername(data);
break;
case 2:
user.setPhone(data);
break;
default:
return null;
}
return userMapper.selectCount(user) == 0;
}
}
(4)测试
我们在数据库插入一条假数据:
然后在浏览器调用接口,测试:
http://localhost:8088/check/admin/1
4.发送短信功能
短信微服务已经准备好,我们就可以继续编写用户中心接口了。
(1)接口说明
这里的业务逻辑是这样的:
-
1)我们接收页面发送来的手机号码
-
2)生成一个随机验证码
-
3)将验证码保存在服务端(redis)
-
4)发送短信,将验证码发送到用户手机
(2)controller
/*
发送短信
*/
@PostMapping(“code”)
public ResponseEntity sendCode(@RequestParam(“phone”) String phone){
userService.sendCode(phone);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
(3)service
这里的逻辑会稍微复杂:
-
生成随机验证码
-
将验证码保存到Redis中,用来在注册的时候验证
-
发送验证码到
ly-sms-service
服务,发送短信
因此,我们需要引入AMQP:
因此,我们需要引入AMQP:
org.springframework.boot
spring-boot-starter-amqp
添加RabbitMQ和Redis配置:
spring:
redis:
host: 192.168.206.66
rabbitmq:
host: 192.168.206.66
username: leyou
password: leyou
virtual-host: /leyou
template:
retry:
enabled: true
initial-interval: 10000ms
max-interval: 210000ms
multiplier: 2
publisher-confirms: true
另外还要用到工具类,生成6位随机码,这个我们封装到了ly-common
中,因此需要引入依赖:
引入common
com.leyou.common
ly-common
${leyou.latest.version}
引入Redis
org.springframework.boot
spring-boot-starter-data-redis
Service代码:
package com.leyou.user.service;
import com.leyou.common.utils.NumberUtils;
import com.leyou.item.pojo.User;
import com.leyou.user.mapper.UserMapper;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.annotation.KeySql;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private AmqpTemplate amqpTemplate;
@Autowired
private StringRedisTemplate redisTemplate;
private static final String KEY_PREFIX = “user:verify☎️”;
public Boolean checkData(String data, Integer type) {
User user = new User();
//判断数据类型
switch (type){
case 1:
user.setUsername(data);
break;
case 2:
user.setPhone(data);
break;
default:
return null;
}
return userMapper.selectCount(user) == 0;
}
public void sendCode(String phone) {
//生成key
String key = KEY_PREFIX +phone;
//生成验证码
String code = NumberUtils.generateCode(6);
Map<String ,String> msg = new HashMap<>();
msg.put(“phone”,phone);
msg.put(“code”,code);
//发送验证码
amqpTemplate.convertAndSend(“ly.sms.exchange”,“sms.verify.code”,msg);
//保存验证码
redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
}
}
(4)测试
发送成功
5.注册功能
(1)接口说明
(2)controller
@PostMapping(“register”)
public ResponseEntity register(User user,@RequestParam(“code”) String code){
Boolean bool = userService.register(user,code);
if(bool == null || !bool){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
return new ResponseEntity<>(HttpStatus.CREATED);
}
(3)service
基本逻辑:
-
1)校验短信验证码
-
2)生成盐
-
3)对密码加密
-
4)写入数据库
-
5)删除Redis中的验证码
1)在ly-common创建CodecUtils工具类
引入依赖
commons-codec
commons-codec
创建CodecUtils
package com.leyou.common.utils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.UUID;
public class CodecUtils {
public static String md5Hex(String data,String salt) {
if (StringUtils.isBlank(salt)) {
salt = data.hashCode() + “”;
}
return DigestUtils.md5Hex(salt + DigestUtils.md5Hex(data));
}
public static String shaHex(String data, String salt) {
if (StringUtils.isBlank(salt)) {
salt = data.hashCode() + “”;
}
return DigestUtils.sha512Hex(salt + DigestUtils.sha512Hex(data));
}
public static String generateSalt(){
return StringUtils.replace(UUID.randomUUID().toString(), “-”, “”);
}
}
2)完善
public Boolean register(User user, String code) {
String key = KEY_PREFIX + user.getPhone();
//从redis获取验证码
String codeCache = redisTemplate.opsForValue().get(key);
if(!code.equals(codeCache)){
return false;
}
user.setId(null);
user.setCreated(new Date());
//生成盐
String salt = CodecUtils.generateSalt();
user.setSalt(salt);
//对密码进行加密
user.setPassword(CodecUtils.md5Hex(user.getPassword(),salt));
//写入数据库
Boolean boo = userMapper.insertSelective(user) == 1;
if(boo){
try {
redisTemplate.delete(key);
}catch (Exception e){
}
}
return boo;
}
(4)测试
先发送验证码
注册成功
6.根据用户名和密码查询用户
(1)接口说明
功能说明
查询功能,根据参数中的用户名和密码查询指定用户
接口路径
GET /query
参数说明:
form表单格式
| 参数 | 说明 | 是否必须 | 数据类型 | 默认值 |
| — | — | — | — | — |
| username | 用户名,格式为4~30位字母、数字、下划线 | 是 | String | 无 |
| password | 用户密码,格式为4~30位字母、数字、下划线 | 是 | String | 无 |
返回结果:
用户的json格式数据
{
“id”: 6572312,
“username”:“test”,
“phone”:“13688886666”,
“created”: 1342432424
}
状态码:
-
200:注册成功
-
400:用户名或密码错误
-
500:服务器内部异常,注册失败
(2)controller
/**
-
根据用户名和密码查询用户
-
@param username
-
@param password
-
@return
*/
@GetMapping(“query”)
public ResponseEntity queryUser(
@RequestParam(“username”) String username,
@RequestParam(“password”) String password
) {
User user = this.userService.queryUser(username, password);
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
return ResponseEntity.ok(user);
}
标签:Vue,Java,String,网络商城,leyou,user,org,import,data From: https://blog.csdn.net/vx_vip204888/article/details/142431623