第1章-系统设计与工程搭建
1 需求分析
1.1 十次方简介
《十次方》是程序员的专属社交平台,包括头条、问答、活动、交友、吐槽、招聘六大 频道。 十次方名称的由来:2的10次方为1024,程序员都懂的。 如果你是一位技术大咖,那么赶快发布文章,增加知名度吧。 如果你是一名技术小白,那么赶快到问答频道寻求帮助的,这里高手如云哦!
如果你不想错过各种技术交流会,那么请经常关注活动频道吧~ 如果你还是单身,那么赶快到交友频道找到你心仪的另一半。 如果你有太多的苦恼,那么赶快吐个槽吧~ 如果你正在找工作或是想跳槽拿高薪,那么来招聘频道淘金吧~
2.项目前期准备
2.1 开发环境要求
JDK1.8 数据库
mysql 5.7
开发工具 idea 2019.3.3
maven版本3.3.9
docker 最新版本
centos7 VMware Workstation Pro 12
我们的mysql使用的是docker环境的
2.2 MYSQL建库建表(容器)
(1)下载镜像
docker pull centos/mysql‐57‐centos7
(2)创建容器
docker run -di --name=tensquare_mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 centos/mysql-57-centos7
(3)navicat连接MYSQL
3. 十次方工程搭建
3.1 搭建父工程
(1)选择菜单file-new project ,弹出窗口中左侧菜单选择Maven ,点击next按钮
(2)填写GroupId 和ArtifacetId ,点击next按钮
(3)点击Finish 完成
(4)删除src文件夹
(5)修改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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tensquare</groupId>
<artifactId>tensquare_parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>tensquare_parent</name>
<description>十次方项目</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF‐ 8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF‐ 8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
</dependencies>
<repositories>
<repository>
<id>spring‐snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring‐milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring‐snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring‐milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
(6)当IDEA右下角弹出提示 ,点击Enable Auto-Import 自动导入依赖
3.2 搭建公共子模块
3.2.1 搭建子模块步骤
搭建公共子模块 tensquare_common
(1)右键点击工程,弹出菜单选择 New -Module 弹出窗口选择Maven ,点击next按钮
(2)点击finish
3.2.2 创建返回结果实体类
(1)新建entity包,包下创建类Result,用于控制器类返回结果
package entity;
public class Result {
private boolean flag;
private Integer code;
private String message;
private Object data;
public Result(boolean flag, Integer code, String message, Object data) {
super();
this.flag = flag;
this.code = code;
this.message = message;
this.data = data;
}
public Result(boolean flag, Integer code, String message) {
super();
this.flag = flag;
this.code = code;
this.message = message;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
(2)创建类PageResult ,用于返回分页结果
package entity;
import java.util.List;
public class PageResult<T> {
private Long total;
private List<T> rows;
public PageResult(Long total, List<T> rows) {
super();
this.total = total;
this.rows = rows;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
}
3.2.3 返回码定义类
package entity;
/**
* 状态
*/
public class StatusCode {
public static final int OK=20000;//成功
public static final int ERROR =20001;//失败
public static final int LOGINERROR =20002;//用户名或密码错误
public static final int ACCESSERROR =20003;//权限不足
public static final int REMOTEERROR =20004;//远程调用失败
public static final int REPERROR =20005;//重复操作
}
3.2.4 分布式ID生成器
由于我们的数据库在生产环境中要分片部署(MyCat),所以我们不能使用数据库本 身的自增功能来产生主键值,只能由程序来生成唯一的主键值。我们采用的是开源的 twitter( 非官方中文惯称:推特.是国外的一个网站,是一个社交网络及微博客服务) 的 snowflake (雪花)算法。
默认情况下41bit的时间戳可以支持该算法使用到2082年,10bit的工作机器id可以 支持1024台机器,序列号支持1毫秒产生4096个自增序列id . SnowFlake的优点是,整 体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID 作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右
package util;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
/**
* <p>名称:IdWorker.java</p>
* <p>描述:分布式自增长ID</p>
* <pre>
* Twitter的 Snowflake JAVA实现方案
* </pre>
* 核心代码为其IdWorker这个类实现,其原理结构如下,我分别用一个0表示一位,用—分割开部分的作用:
* 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000
* 在上面的字符串中,第一位为未使用(实际上也可作为long的符号位),接下来的41位为毫秒级时间,
* 然后5位datacenter标识位,5位机器ID(并不算标识符,实际是为线程标识),
* 然后12位该毫秒内的当前毫秒内的计数,加起来刚好64位,为一个Long型。
* 这样的好处是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由datacenter和机器ID作区分),
* 并且效率较高,经测试,snowflake每秒能够产生26万ID左右,完全满足需要。
* <p>
* 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
*
* @author Polim
*/
public class IdWorker {
// 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
private final static long twepoch = 1288834974657L;
// 机器标识位数
private final static long workerIdBits = 5L;
// 数据中心标识位数
private final static long datacenterIdBits = 5L;
// 机器ID最大值
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 数据中心ID最大值
private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒内自增位
private final static long sequenceBits = 12L;
// 机器ID偏左移12位
private final static long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private final static long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
/* 上次生产id时间戳 */
private static long lastTimestamp = -1L;
// 0,并发控制
private long sequence = 0L;
private final long workerId;
// 数据标识id部分
private final long datacenterId;
public IdWorker(){
this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
}
/**
* @param workerId
* 工作机器ID
* @param datacenterId
* 序列号
*/
public IdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
/**
* 获取下一个ID
*
* @return
*/
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
// 当前毫秒内,则+1
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// 当前毫秒内计数满了,则等待下一秒
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
// ID偏移组合生成最终的ID,并返回ID
long nextId = ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
return nextId;
}
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
/**
* <p>
* 获取 maxWorkerId
* </p>
*/
protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
StringBuffer mpid = new StringBuffer();
mpid.append(datacenterId);
String name = ManagementFactory.getRuntimeMXBean().getName();
if (!name.isEmpty()) {
/*
* GET jvmPid
*/
mpid.append(name.split("@")[0]);
}
/*
* MAC + PID 的 hashcode 获取16个低位
*/
return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
}
/**
* <p>
* 数据标识id部分
* </p>
*/
protected static long getDatacenterId(long maxDatacenterId) {
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
id = ((0x000000FF & (long) mac[mac.length - 1])
| (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
} catch (Exception e) {
System.out.println(" getDatacenterId: " + e.getMessage());
}
return id;
}
}
4. 基础微服务-标签CRUD
4.1模块搭建
(1)搭建基础微服务模块tensquare_base , pom.xml引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.tensquare</groupId>
<artifactId>tensquare_common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
(2)创建启动类
package com.tensquare.search.base;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import util.IdWorker;
@SpringBootApplication
public class BaseApplication {
public static void main(String[] args) {
SpringApplication.run(BaseApplication.class, args);
}
@Bean
public IdWorker idWorkker(){
return new IdWorker(1, 1);
}
}
(3)在resources下创建application.yml
server:
port: 9001
spring:
application:
name: tensquare-base
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.11.129:3306/tensquare_base?characterEncoding=UTF8
username: root
password: 123456
jpa:
database: MySQL
show-sql: true
4.2 标签管理-CRUD
4.2.1 表结构分析
表名称:tb_label
4.2.2 CRUD的实现
(1)实体类
创建com.tensquare.base包,包下创建pojo包 ,包下创建实体类Label
package com.tensquare.search.base.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* 实体类
* @author Administrator
*
*/
@Entity
@Table(name="tb_label")
public class Label implements Serializable{
@Id
private String id;//标签ID
private String labelname;//标签名称
private String state;//状态
private Long count;//使用数量
private String recommend;//是否推荐
private Long fans;//粉丝数
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLabelname() {
return labelname;
}
public void setLabelname(String labelname) {
this.labelname = labelname;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
public String getRecommend() {
return recommend;
}
public void setRecommend(String recommend) {
this.recommend = recommend;
}
public Long getFans() {
return fans;
}
public void setFans(Long fans) {
this.fans = fans;
}
}
(3)创建数据访问接口
com.tensquare.base包下创建dao包,包下创建LabelDao接口
package com.tensquare.search.base.dao;
import com.tensquare.search.base.pojo.Label;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* 数据访问接口
* @author Administrator
*
*/
public interface LabelDao extends JpaRepository<Label,String>,JpaSpecificationExecutor<Label>{
}
JpaRepository提供了基本的增删改查 JpaSpecificationExecutor用于做复杂的条件查询
(4)业务逻辑类 com.tensquare.base包下创建service包,包下创建LabelService类。 在这个类中,我们 实现基本的增删改查功能
package com.tensquare.search.base.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.IdWorker;
import com.tensquare.search.base.dao.LabelDao;
import com.tensquare.search.base.pojo.Label;
/**
* 服务层
*
* @author Administrator
*
*/
@Service
public class LabelService {
@Autowired
private LabelDao labelDao;
@Autowired
private IdWorker idWorker;
/**
* 查询全部列表
* @return
*/
public List<Label> findAll() {
return labelDao.findAll();
}
/**
* 条件查询+分页
* @param whereMap
* @param page
* @param size
* @return
*/
public Page<Label> findSearch(Map whereMap, int page, int size) {
Specification<Label> specification = createSpecification(whereMap);
PageRequest pageRequest = PageRequest.of(page-1, size);
return labelDao.findAll(specification, pageRequest);
}
/**
* 条件查询
* @param whereMap
* @return
*/
public List<Label> findSearch(Map whereMap) {
Specification<Label> specification = createSpecification(whereMap);
return labelDao.findAll(specification);
}
/**
* 根据ID查询实体
* @param id
* @return
*/
public Label findById(String id) {
return labelDao.findById(id).get();
}
/**
* 增加
* @param label
*/
public void add(Label label) {
label.setId( idWorker.nextId()+"" );
labelDao.save(label);
}
/**
* 修改
* @param label
*/
public void update(Label label) {
labelDao.save(label);
}
/**
* 删除
* @param id
*/
public void deleteById(String id) {
labelDao.deleteById(id);
}
/**
* 动态条件构建
* @param searchMap
* @return
*/
private Specification<Label> createSpecification(Map searchMap) {
return new Specification<Label>() {
@Override
public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicateList = new ArrayList<Predicate>();
// 标签ID
if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%"));
}
// 标签名称
if (searchMap.get("labelname")!=null && !"".equals(searchMap.get("labelname"))) {
predicateList.add(cb.like(root.get("labelname").as(String.class), "%"+(String)searchMap.get("labelname")+"%"));
}
// 状态
if (searchMap.get("state")!=null && !"".equals(searchMap.get("state"))) {
predicateList.add(cb.like(root.get("state").as(String.class), "%"+(String)searchMap.get("state")+"%"));
}
// 是否推荐
if (searchMap.get("recommend")!=null && !"".equals(searchMap.get("recommend"))) {
predicateList.add(cb.like(root.get("recommend").as(String.class), "%"+(String)searchMap.get("recommend")+"%"));
}
return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));
}
};
}
}
(5)控制器类 com.tensquare.user包下创建controller包,创建LabelController
package com.tensquare.search.base.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tensquare.search.base.pojo.Label;
import com.tensquare.search.base.service.LabelService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
/**
* 控制器层
* @author Administrator
*
*/
@RestController
@CrossOrigin
@RequestMapping("/label")
public class LabelController {
@Autowired
private LabelService labelService;
/**
* 查询全部数据
* @return
*/
@RequestMapping(method= RequestMethod.GET)
public Result findAll(){
return new Result(true,StatusCode.OK,"查询成功",labelService.findAll());
}
/**
* 根据ID查询
* @param id ID
* @return
*/
@RequestMapping(value="/{id}",method= RequestMethod.GET)
public Result findById(@PathVariable String id){
return new Result(true,StatusCode.OK,"查询成功",labelService.findById(id));
}
/**
* 分页+多条件查询
* @param searchMap 查询条件封装
* @param page 页码
* @param size 页大小
* @return 分页结果
*/
@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
Page<Label> pageList = labelService.findSearch(searchMap, page, size);
return new Result(true,StatusCode.OK,"查询成功", new PageResult<Label>(pageList.getTotalElements(), pageList.getContent()) );
}
/**
* 根据条件查询
* @param searchMap
* @return
*/
@RequestMapping(value="/search",method = RequestMethod.POST)
public Result findSearch( @RequestBody Map searchMap){
return new Result(true,StatusCode.OK,"查询成功",labelService.findSearch(searchMap));
}
/**
* 增加
* @param label
*/
@RequestMapping(method=RequestMethod.POST)
public Result add(@RequestBody Label label ){
labelService.add(label);
return new Result(true,StatusCode.OK,"增加成功");
}
/**
* 修改
* @param label
*/
@RequestMapping(value="/{id}",method= RequestMethod.PUT)
public Result update(@RequestBody Label label, @PathVariable String id ){
label.setId(id);
labelService.update(label);
return new Result(true,StatusCode.OK,"修改成功");
}
/**
* 删除
* @param id
*/
@RequestMapping(value="/{id}",method= RequestMethod.DELETE)
public Result delete(@PathVariable String id ){
labelService.deleteById(id);
return new Result(true,StatusCode.OK,"删除成功");
}
}
4.3 公共异常处理
为了使我们的代码更容易维护,我们创建一个类集中处理异常
在com.tensquare.base.controller包下创建公共异常处理类BaseExceptionHandler
package com.tensquare.search.base.controller;
import entity.Result;
import entity.StatusCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 统一异常处理类
*/
@ControllerAdvice
public class BaseExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result error(Exception e){
e.printStackTrace();
return new Result(false, StatusCode.ERROR, "执行出错");
}
}
4.4 跨域处理
跨域是什么?浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、 协议任一不同,都是跨域 。我们是采用前后端分离开发的,也是前后端分离部署的,必然会存在跨域问题。 怎么解决跨域?很简单,只需要在controller类上添加注解 @CrossOrigin
即可!这个注解其实是CORS的实现。