# MicroService
**Repository Path**: pcpcode/MicroService
## Basic Information
- **Project Name**: MicroService
- **Description**: 记录微服务的集成过程
- **Primary Language**: Unknown
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2019-12-29
- **Last Updated**: 2020-12-19
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# [项目源码地址](https://gitee.com/pcpcode/SSM-Teamplate) #
# 1.Git/TortoiseGit
> 需要生成密钥使用,并在配置文件.gitconfig中配置:
[credential]
helper = store
这样拉取代码时就不必一直登录了
# 2.IDEA社区版
> 需要下载YAML,Spring Assistant两个插件,yml文件才有提示
> 然后配置好jdk8,maven
# 3.Maven配置
> 指定本地仓库
D:\idea\MavenRepository
> 指定远程仓库
alimaven
central
aliyun maven
http://maven.aliyun.com/nexus/content/repositories/central/
repo1
central
Human Readable Name for this Mirror.
http://repo1.maven.org/maven2/
repo2
central
Human Readable Name for this Mirror.
http://repo2.maven.org/maven2/
# 4.Swagger2 项目连接 [FeignAndHystrix](https://gitee.com/pcpcode/SSM-Teamplate/tree/master/FeignAndHystrix)和[MybatisPlus](https://gitee.com/pcpcode/SSM-Teamplate/tree/master/MybatisPlus)
> PS:当使用jar查看文档时,可使用如下命令开/关文档
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
org.springframework.restdocs
spring-restdocs-mockmvc
test
io.springfox
springfox-staticdocs
2.6.1
org.springframework.boot
spring-boot-maven-plugin
io.github.swagger2markup
swagger2markup-maven-plugin
1.3.7
http://127.0.0.1:8082/v2/api-docs
src/main/doc/apiall
CONFLUENCE_MARKUP
org.asciidoctor
asciidoctor-maven-plugin
1.6.0
src/main/doc/apiall
src/main/doc/html
html
coderay
left
jcenter-snapshots
jcenter
http://oss.jfrog.org/artifactory/oss-snapshot-local/
jcenter-releases
jcenter
http://jcenter.bintray.com
false
## 4.2 Swagger的yml设置
# 上线需要关闭,设置为false
swagger:
enabled: true
## 4.3 config配置 ##
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置
@Value(value = "${swagger.enabled}")
Boolean swaggerEnabled;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerEnabled) // 是否开启
.apiInfo(apiInfo())
//去掉默认返回的状态码和message
.useDefaultResponseMessages(false)
.select()
//扫描swagger2注解所在的包,通常是controller
.apis(RequestHandlerSelectors.basePackage("com.pcp.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("互调与熔断Api")
.contact(new Contact("文档作者:PCP", "", "1361815282@qq.com"))
.version("1.0.0")
.description("路由路径:http://127.0.0.1:8092/api/feignroute/feign")
.build();
}
}
## 4.4 注解说明 ##
> paramType:
>> header --> 请求参数的获取:@RequestHeader
>> query --> 请求参数的获取:@RequestParam
>> path(用于restful接口)--> 请求参数的获取:@PathVariable
>> body(--> 请求参数的获取:@RequestBody
>> form(不常用)
> responseContainer(@ApiResponse里的属性):
>> List
>> Set
>> Map
@Api(tags = "互调与熔断使用例子API")
@ApiOperation(value = "用户信息",notes = "根据姓名和年龄得到用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "name",value = "用户姓名",paramType = "query",dataType = "String"),
@ApiImplicitParam(name = "age",value = "用户年龄",paramType = "query",dataType = "Integer"),
})
@ApiResponses({
@ApiResponse(code = 2001,message = "失败",response = xxError.class)
})
## 4.5 额外说明
> 当获取不到GitHub内容时,可在当前项目的pom中设置如下远程仓库:
jcenter-snapshots
jcenter
http://oss.jfrog.org/artifactory/oss-snapshot-local/
jcenter-releases
jcenter
http://jcenter.bintray.com
false
jcentral
bintray
http://jcenter.bintray.com
false
jcenter-snapshots
jcenter
http://oss.jfrog.org/artifactory/oss-snapshot-local/
# 5.Mybatis Plus 项目连接 [Mybatis Plus](https://gitee.com/pcpcode/SSM-Teamplate/tree/master/Mysql-MoreDataSource)
> 安装MybatisX插件,作用:
>> Java 与 XML 调回跳转
>> Mapper 方法自动生成 XML
## 5.1 mysql数据库与自动代码生成器依赖
> 自动代码生成器类:[CodeGenerator.java](https://gitee.com/pcpcode/MicroService/blob/master/CodeGenerator.java)
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
8.0.18
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
true
com.baomidou
mybatis-plus-boot-starter
3.3.0
com.baomidou
mybatis-plus-generator
3.3.0
org.freemarker
freemarker
2.3.29
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
p6spy
p6spy
3.8.7
org.springframework.cloud
spring-cloud-starter-openfeign
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
## 5.2 mysql额外说明 ##
### 5.2.1 mysql8.0 ###
> mysql8.0的驱动是:com.mysql.cj.jdbc.Driver而不是com.mysql.jdbc.Driver
> 连接url时,需要加上:useSSL=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
### 5.2.2 连接数修改 ###
1.只在当前服务进程中有效,一旦MySQL重启,就会恢复到初始状态
> 查看MySQL最大连接数
>> show variables like '%max_connections%';
>
> 修改最大连接数
>> set GLOBAL max_connections = 600;
2.永久有效的修改
> 打开MySQL配置文件/etc/my.cnf,添加配置项max_connections=600,保存。
> 这样,最大连接数就被设置成了600,重启MySQL后生效
## 5.3 自动代码生成器需要注意的点 ##
说明 | 图片
:-: | :-:
执行main方法,按提示填写模块名和表 | 
配置@MapperScan注解和mybatis.mapper-locations,两者缺一不可 |
@MapperScan | 
mybatis.mapper-locations | 
mapper的xml放在resource下,官网说必须用classpath\*。需要注意的是,一定要写全包名,再写 \*.xml,否则可能读取不到xml |
结构间的依赖调用说明 | UserController 调用 UserServiceImpl 调用 baseMapper(里面封装了UserMapper及其xml)
其中IUserService不用管了,它只是起了封装作用。|
## 5.4 Hikari单数据源配置及简单调用使用 ##
### 5.4.1 yml配置 ###
server:
port: 8086
swagger:
enabled: true
mybatis-plus:
mapper-locations:
- classpath*:mapper/mine/*.xml
spring:
application:
name: MybatisPlus
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mine?useUnicode=true&useSSL=false&characterEncoding=utf8&&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
username: root
password: 123456
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimum-idle: 5
maximum-pool-size: 15
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8090/eureka/ # 客户端注册地址
instance: # 设置微服务调用地址为IP优先(缺省为false)
prefer-ip-address: true
# 心跳时间,即服务续约间隔时间(缺省为30s)
lease-renewal-interval-in-seconds: 30
# 发呆时间,即服务续约到期时间(缺省为90s)
lease-expiration-duration-in-seconds: 90
feign: # feign默认的超时时间是1秒,重试1次.openfeign默认依赖了ribbon
hystrix: # hystrix的超时时长,默认为1秒,太短了
enabled: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 15000 # 断路器的超时时间需要大于ribbon[ReadTimeout+ConnectionTimeout]*2的超时时间,不然重试没有意义
ribbon:
ReadTimeout: 3000 # 处理请求的超时时间,默认为1秒
ConnectionTimeout: 3000 # 连接建立的超时时长,默认1秒
OkToRetryOnAllOperations: true # 是否对所有操作都重试,默认false
MaxAutoRetriesNextServer: 0 # 重试负载均衡其他实例的最大重试次数,不包括首次调用,默认为0次
MaxAutoRetries: 1 # 同一台实例的最大重试次数,但是不包括首次调用,默认为1次
### 5.4.2 简单调用使用 ###
说明 | 图片 |
:---:|:---:
controller | 
service | 
mapper | 
mappersql | 
## 5.5 Hikari配置多数据源(不建议一个模块配多数据源,怕有事务或其他冲突。建议每个模块一个数据源,各个模块openfeign互相调用) [Mysql-MoreDataSource](https://gitee.com/pcpcode/SSM-Teamplate/tree/master/Mysql-MoreDataSource)
> 实际开发中,我们需要用到多个数据库,因此很有必要引入多数据源配置
### 5.5.1 多数据源的yml配置 ###
server:
port: 8084
# Mapper包扫描
#mybatis-plus:
# mapper-locations:
# - classpath*:mapper/mine/*.xml
spring:
datasource:
# driver-class-name: com.mysql.cj.jdbc.Driver
# 在Spring boot 2.+的版本中,不需要配置driverClassName,会根据url来检测加载哪个driverClassName
# 据源one
one:
jdbc-url: jdbc:mysql://localhost:3306/mine?useUnicode=true&useSSL=false&characterEncoding=utf8&&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
username: root
password: 123456
# 设置最小和最大连接数
minimum-idle: 5
maximum-pool-size: 15
# 数据源two
two:
jdbc-url: jdbc:mysql://localhost:3306/pc?useUnicode=true&useSSL=false&characterEncoding=utf8&&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull
username: root
password: 123456
# 设置最小和最大连接数
minimum-idle: 5
maximum-pool-size: 15
### 5.5.2 配置各个数据源的config ###
#### 5.5.2.1 one数据源(默认为主数据源)的config配置 ####
/**
*
* @MapperScan 扫描mapper所在路径,也就是常说的DAO层
*/
@Configuration
@MapperScan(basePackages = "com.pcp.mine.mapper.one",sqlSessionFactoryRef = "oneSqlSessionFactory")
public class OneDataSourceConfig {
/**
* @Bean 注册Bean对象
* @Primary 表示默认数据源
* @ConfigurationProperties 读取properties中的配置参数映射成为一个对象
*/
@Bean(name = "oneDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.one")
public HikariDataSource getOneDateSource() {
return new HikariDataSource();
}
/**
* @param datasource 数据源
* @return SqlSessionFactory
* @Primary 默认SqlSessionFactory
*/
@Bean(name = "oneSqlSessionFactory")
@Primary
public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource datasource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
//mybatis扫描xml所在位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/mine/one/*.xml"));
return bean.getObject();
}
/**
* SqlSessionTemplate是个线称安全的类,每运行一个SqlSessionTemplate时,它就会重新获取一个新的SqlSession
*/
@Bean("oneSessionTemplate")
@Primary
public SqlSessionTemplate oneSqlSessionTemplate(@Qualifier("oneSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
/**
* 事务
*/
@Bean
@Primary
public PlatformTransactionManager oneTransactionManager(@Qualifier("oneDataSource") DataSource datasource) {
return new DataSourceTransactionManager(datasource);
}
}
#### 5.5.2.2 two数据源(副数据源)的config配置 ####
/**
*
* @MapperScan 扫描mapper所在路径,也就是常说的DAO层
*/
@Configuration
@MapperScan(basePackages = "com.pcp.mine.mapper.two",sqlSessionFactoryRef = "twoSqlSessionFactory")
public class TwoDataSourceConfig {
/**
* @Bean 注册Bean对象
* @Primary 表示默认数据源
* @ConfigurationProperties 读取properties中的配置参数映射成为一个对象
*/
@Bean(name = "twoDataSource")
@ConfigurationProperties(prefix = "spring.datasource.two")
public HikariDataSource getTwoDateSource() {
return new HikariDataSource();
}
/**
* @param datasource 数据源
* @return SqlSessionFactory
* @Primary 默认SqlSessionFactory
*/
@Bean(name = "twoSqlSessionFactory")
public SqlSessionFactory twoSqlSessionFactory(@Qualifier("twoDataSource") DataSource datasource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
//mybatis扫描xml所在位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/mine/two/*.xml"));
return bean.getObject();
}
/**
* SqlSessionTemplate是个线称安全的类,每运行一个SqlSessionTemplate时,它就会重新获取一个新的SqlSession
*/
@Bean("twoSessionTemplate")
public SqlSessionTemplate twoSqlSessionTemplate(@Qualifier("twoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
/**
* 事务
*/
@Bean
public PlatformTransactionManager twoTransactionManager(@Qualifier("twoDataSource") DataSource datasource) {
return new DataSourceTransactionManager(datasource);
}
}
### 5.5.3 注意源码结构变化 ###
> 1.需要注意的是,最好将不同Mapper接口(DAO层)和对应的Mapper.xml分别放在不同的文件夹,以免混淆,以此区分来维护代码。结构如下图所示:

> 2.配置了多数据源后,只有默认的数据源才能使用Mybatis Plus的baseMapper,因此在xServiceImpl中,推荐使用注入xMapper方式调用sql,不推荐使用baseMapper.如图:

### 5.5.4 Mapper CRUD基本使用 ###
#### Select ####
// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);
// 查询(根据ID 批量查询)
List selectBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList);
// 根据 entity 条件,查询全部记录
List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper);
// 查询(根据 columnMap 条件)
List selectByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
// 根据 Wrapper 条件,查询全部记录
List