发布时间:2024-07-13 14:01
今天小白将从零亲手搭建spring Boot+MyBatis-Plus +mysql框架的微服务。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>${velocity.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- mybatis-plus end -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<mybatis-plus-boot-starter.version>3.3.0</mybatis-plus-boot-starter.version>
<mysql.version>5.1.47</mysql.version>
<druid.version>1.1.20</druid.version>
</properties>
package yooo.yun.com.user.controller.saas;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import yooo.yun.com.common.api.ApiCode;
import yooo.yun.com.common.api.ApiResult;
import yooo.yun.com.common.entity.enums.LoginTypeEnum;
import yooo.yun.com.common.entity.pojo.UserPoJo;
import yooo.yun.com.common.entity.request.UserLoginReq;
import yooo.yun.com.common.entity.request.UserReq;
import yooo.yun.com.user.service.UserService;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;
/**
* @author WangJiao
* @since 2020/10/14
*/
@Slf4j
@RequestMapping(value = "/saas/user")
@RestController("sUserC")
public class UserController {
@Resource private UserService service;
/**
* 用户注册
*
* @param req 注册信息
* @return obj
*/
@PostMapping("/register")
@ApiOperation("注册")
public ApiResult register(@Valid @RequestBody UserReq req) {
log.info("register:[req:{}]", JSON.toJSONString(req));
if (!Objects.equals(req.getPassword(), req.getRePassword())) {
return ApiResult.fail(ApiCode.USER_TWO_PASSWORDS_INCONSISTENT);
}
UserPoJo findUser = service.getByTel(req.getTel());
if (Objects.nonNull(findUser)) {
return ApiResult.fail(ApiCode.USER_ACCOUNT_REGISTERED);
}
// md5加密
req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
boolean res = service.save(UserPoJo.of(req));
log.info("register:[res:{}]", res);
return ApiResult.ok(res);
}
/**
* 用户登录
*
* @param req req
* @return res
*/
@PostMapping("/login")
@ApiOperation("登录")
public ApiResult login(@Valid @RequestBody UserLoginReq req) {
log.info("login:[req:{}]", req);
String tel = req.getTel();
UserPoJo findUser = service.getByTel(tel);
if (Objects.isNull(findUser)) {
return ApiResult.fail(ApiCode.USER_ACCOUNT_NOT_EXIST);
}
if (!Objects.equals(
DigestUtils.md5DigestAsHex(req.getPassword().getBytes()), findUser.getPassword())) {
return ApiResult.fail(ApiCode.USER_PASSWORDS_ERROR);
}
return ApiResult.ok(service.login(findUser, LoginTypeEnum.SAAS.getValue()));
}
/**
* 获取用户详情
*
* @param id id
* @return res
*/
@GetMapping("/{id}")
@ApiOperation("获取用户详情")
public ApiResult detail(@PathVariable(value = "id") long id) {
log.info("detail:[id:{}]", id);
return ApiResult.ok(service.getById(id));
}
/**
* 删除用户信息
*
* @param id id
* @return res
*/
@DeleteMapping("/delete/{id}")
@ApiOperation("删除用户信息")
public ApiResult delete(@PathVariable(value = "id") long id) {
log.info("delete:[id:{}]", id);
return ApiResult.ok(service.removeById(id));
}
}
package yooo.yun.com.user.service;
import yooo.yun.com.common.entity.pojo.UserPoJo;
import yooo.yun.com.common.service.BaseService;
/**
* @author WangJiao
* @since 2020/11/12
*/
public interface UserService extends BaseService<UserPoJo> {
/**
* query user info by tel
*
* @param tel the tel
* @return user
*/
UserPoJo getByTel(String tel);
int testE(int status);
/**
* 登录
*
* @param findUser findUser
* @param loginType loginType
* @return token
*/
String login(UserPoJo findUser, String loginType);
}
package yooo.yun.com.user.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import yooo.yun.com.common.entity.enums.UserRoleEnum;
import yooo.yun.com.common.entity.pojo.UserPoJo;
import yooo.yun.com.common.service.Impl.BaseServiceImpl;
import yooo.yun.com.common.utils.JWTUtil;
import yooo.yun.com.user.mapper.UserMapper;
import yooo.yun.com.user.service.UserService;
import javax.annotation.Resource;
/**
* @author WangJiao
* @since 2020/11/12
*/
@Slf4j
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserPoJo> implements UserService {
@Resource private UserMapper mapper;
@Override
public UserPoJo getByTel(String tel) {
log.info("getByTel:[tel:{}]", tel);
return mapper.selectOne(Wrappers.<UserPoJo>lambdaQuery().eq(UserPoJo::getTel, tel));
}
@Override
public int testE(int status) {
int num = 0;
return status / num;
}
@Override
public String login(UserPoJo findUser, String loginType) {
// TODO: 2020/11/25/025 其他业务逻辑处理
String token =
JWTUtil.generateSaasToken(findUser.getId(), UserRoleEnum.ADMIN.getValue(), null, loginType);
log.info("login:[token:{}]", token);
return token;
}
}
package yooo.yun.com.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
import yooo.yun.com.common.entity.pojo.UserPoJo;
/**
* @author WangJiao
* @since 2020/11/12
*/
@Repository
public interface UserMapper extends BaseMapper<UserPoJo> {
}
server:
port: 5050
servlet:
context-path: /user
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8080/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
############################### mysql start #################################
spring:
application:
name: cloud-user
freemarker:
enabled: false
thymeleaf:
cache: false
datasource:
url: jdbc:mysql://localhost:3306/cloud_user?characterEncoding=utf8&generateSimpleParameterMetadata=true&connectTimeout=5000&useSSL=false
username: ****
password: ****
############################### mysql end #################################
# logback.xml中有详细的日志配置
logging:
config: classpath:logback.xml
############################### mybatis-plus start #################################
mybatis-plus:
# 启动时是否检查MyBatis XML文件是否存在
check-config-location: true
# MyBatis原生配置
configuration:
# 字段名称下划线转驼峰命名
map-underscore-to-camel-case: true
# 打印SQL日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 全局默认主键类型
id-type: id_worker
logic-delete-field: isDelete
# 逻辑已删除值(默认为 1)
logic-delete-value: true # 逻辑已删除值(默认为 1)
# 逻辑未删除值(默认为 0)
logic-not-delete-value: false # 逻辑未删除值(默认为 0)
# mapper xml映射路径
mapper-locations: classpath*:mapper/**/*Mapper.xml
################################ mybatis-plus end ##################################
#################################### Swagger start #################################
# swagger配置
swagger:
base:
package: yooo.yun.com
contact:
email: jiao.wang@cloud.yun
name: wangjiao
url: ''
description: ''
title: spring-demo
url: ''
version: 1.0
#################################### Swagger end ###################################
/**
* 获取用户详情
*
* @param id id
* @return res
*/
@GetMapping("/{id}")
@ApiOperation("获取用户详情")
public ApiResult detail(@PathVariable(value = "id") long id) {
log.info("detail:[id:{}]", id);
return ApiResult.ok(service.getById(id));
}
<!-- lombok使实体类简写get与set方法-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
@RequestMapping(value = "/saas/user")
@RestController注解,相当于@Controller+@ResponseBody两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解,但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面
例子:@RestController(value = “miniUserC”)中的value区分项目中的bean,比如项目中有两个相同的UserController。
提供了对Restful风格的支持
@GetMapping("/{id}")
等价于
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
/**
* 获取用户详情
*
* @param id id
* @return res
*/
@GetMapping("/{id}")
@ApiOperation("获取用户详情")
public ApiResult detail(@PathVariable(value = "id") long id) {
log.info("detail:[id:{}]", id);
return ApiResult.ok(service.getById(id));
}
@PostMapping("/register")
等价于
@RequestMapping(value = "/register",method = RequestMethod.POST)
/**
* 用户注册
*
* @param req 注册信息
* @return obj
*/
@PostMapping("/register")
@ApiOperation("注册")
public ApiResult register(@Valid @RequestBody UserReq req) {
log.info("register:user register info[req:{}]", JSON.toJSONString(req));
if (!Objects.equals(req.getPassword(), req.getRePassword())) {
return ApiResult.fail(ApiCode.USER_TWO_PASSWORDS_INCONSISTENT);
}
UserPoJo findUser = service.getByTel(req.getTel());
if (Objects.nonNull(findUser)) {
return ApiResult.fail(ApiCode.USER_ACCOUNT_REGISTERED);
}
// md5加密
req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
boolean res = service.save(UserPoJo.of(req));
log.info("register:[res:{}]", res);
return ApiResult.ok(res);
}
@PutMapping("/update/{id}")
等价于
@RequestMapping(value = "/register",method = RequestMethod.POST)
@DeleteMapping("/delete/{id}")
等价于
@RequestMapping(value = "/update/{id}",method = RequestMethod.DELETE)
/**
* 删除用户信息
*
* @param id id
* @return res
*/
@DeleteMapping("/delete/{id}")
@ApiOperation("删除用户信息")
public ApiResult delete(@PathVariable(value = "id") long id) {
log.info("delete:[id:{}]", id);
UserPoJo find = service.getById(id);
if (Objects.isNull(find)) {
return ApiResult.fail(ApiCode.DATA_NOT_EXIST_FAILED_DELETE);
}
return ApiResult.ok(service.removeById(id));
}
:- 学到这里,你就get到了喔
2022云原生网络趋势 | K8s托管整个基础设施、多云、边缘计算、安全等场景,将云原生网络带向新战场
tensorflow------CIFAR10代码训练图像分类
php 创建图像并保存,使用PHP ImageCreateFromJPEG()不允许我重新创建图像:它只生成一次图像,并保存在服务器缓存中,无论...
详解JavaScript中if语句优化和部分语法糖小技巧推荐
【深度学习环境配置】手把手实战配置深度学习环境(win10版)
openharmony北向应用开发实例之HelloWorld
Spring框架系列(2) - Spring简单例子引入Spring要点
人体关节点检测 c++ tensorrt实现openpose mmpose
微信小程序--全局配置文件中的pages,window,taBar属性
Daily Paper(2) Minitaur, an Event-Driven FPGA-Based Spiking Network Accelerator
解决 “TypeError: Cannot read properties of undefined (reading ‘xxx‘)“