主要内容:
- 如何搭建EurekaServer注册中心?要导哪些包?主启动类要加哪些注解?application.yml要写哪些内容?
- 如何搭建ZuulServer网关?要导哪些包?主启动类要加哪些注解?application.yml要写哪些内容?
- 如何搭建ConfigServer?configfiles用来做什么?要导哪些包?主启动类要加哪些注解?application.yml要写哪些内容,和其他服务的配置有什么区别?
- MybatisPlus代码生成器是什么有什么用?是否需要独立为生成器创建模块?要导哪些包?主启动类要加哪些注解?在mybatisplus-config.properties中应该有哪些配置?自动生成代码的GenteratorCode.java大致应该怎么写?
- 如何搭建system-server?要导哪些包?主启动类要加哪些注解?application.yml要写哪些内容?
- swagger有什么用?导哪些包?Zuul集成swagger与其他服务整合swagger有什么区别?
文章目录
EurekaServer注册中心搭建
1.导包
- spring-cloud-starter-netflix-eureka-server:开启eureka服务需要,eureka的服务端他已经集成了spring-boot-starter-web,所以不需要再配了。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
2.配置主启动类
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication1010 {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication1010.class);
}
}
3.配置application.yml
server:
port: 1010
eureka: #Eureka的配置
instance:
hostname: localhost #主机
client: #对Eureka客户端配置
registerWithEureka: false #注册中心自己 , 不准向注册中心自己注册
fetchRegistry: false #注册中心不需要 获取服务的通信地址清单
serviceUrl: #注册中心 服务的注册地址
#defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
defaultZone: http://localhost:1010/eureka/
ZuulServer网关搭建
1.导包
- spring-cloud-starter-netflix-eureka-client:开启eureka服务需要
- spring-cloud-starter-netflix-zuul:开启zuul需要
- spring-boot-starter-web:自动帮我们引入了web模块开发需要的相关jar包
由于现在还没有集成config-server,所以暂时不需要导config相关的包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<!-- 集成Web的jar包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.配置主启动类
@SpringBootApplication
@EnableZuulProxy
public class ZuulServerApplication1020
{
public static void main( String[] args )
{
SpringApplication.run(ZuulServerApplication1020.class);
}
}
3.配置application.yml
配好端口服务名,注册中心的服务端的注册地址,其他的先不管,因为这个文件我们后面要统一交给一个文件夹来管理。
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1010/eureka/ #注册中心服务端的注册地址
instance:
prefer-ip-address: true #使用ip进行注册
instance-id: zuul-server:1020 #服务注册到注册中心的id
server:
port: 1020
#应用的名字
spring:
application:
name: zuul-server
zuul:
#prefix: "/hrm"
ignored-services: "*" #禁止浏览器 使用服务名的方式去访问目标服务
routes:
pay-server: "/pay/**" # pay-server这个服务使用 /pay路径去访问
order-server: "/order/**" #order-server这个服务使用 /order 路径去访问
# http://localhost:5000/hrm/pay/pay/user/20 :访问方式: zuulip:zuul端口/前缀/服务的访问路径/资源路径
host: #zuul主机超时
connect-timeout-millis: 30000 #HTTP连接超时要比Hystrix的大
socket-timeout-millis: 30000 #socket超时
ribbon: #ribbon超时
ReadTimeout: 30000
ConnectTimeout: 30000
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 40000
ConfigServer配置中心搭建
1.创建configfiles文件夹
- 在项目根目录处创建一个configfiles文件夹用于存储application.yml配置文件
- 现在除开注册中心,只有一个zuul服务,我们先在configfiles中添加application-zuul-dev.yml
- 然后将其提交到git远程仓库
2.导包
- spring-cloud-config-server:config-server是服务端,要配这个
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
3.配置主启动类
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication1030 {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication1030.class);
}
}
4.配置application.yml
举个例子,zuul-server的具体配置文件可以放在远程仓库上,而config-server的配置文件只能配置在本地,因为你需要在config-server的配置文件中指定远程仓库的地址及账号密码等,然后zuul-server配置文件指向config-server的配置文件指定具体需要的配置文件名就能从远程仓库拿到需要的配置文件了
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1010/eureka/ #注册中心服务端的注册地址
instance:
prefer-ip-address: true #使用ip进行注册
instance-id: config-server:1030 #服务注册到注册中心的id
server:
port: 1030
#应用的名字
spring:
application:
name: config-server
#码云配置
cloud:
config:
server:
git:
uri: https://gitee.com/myllxy/hrm-parent.git
username: 15892306059
password: 276689237abc
search-paths: configfiles #指定git的具体目录
MybatisPlus代码生成器搭建
1.什么是MybatisPlus
在真实项目开发中我们的服务模块,一般都要进行数据库操作,并且每个domain都有crud,需多次写重复代码。我们使用MybatisPlus,就不用写重复代码,并且还有模板的功能,可以一键生成daomin,query,mapper接口,mapper.xml,service,controller,非常好用。
2.创建hrm-code-generate模块并导包
- velocity-engine-core:需要依靠velocity来生成文件
- mysql-connector-java:需要依靠数据库中的表来生成domain
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!--模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
3.配置mybatisplus-config.properties
#此处为本项目src所在路径(代码生成器输出路径),注意一定是当前项目所在的目录哟
#mapper service controller输出目录
OutputDir=D:/workspacejavaee/hrm-parent/hrm-systemmanage-parent/hrm-systemmanage-service-2010/src/main/java
#mapper.xml SQL映射文件目录
OutputDirXml=D:/workspacejavaee/hrm-parent/hrm-systemmanage-parent/hrm-systemmanage-service-2010/src/main\resources
#domain、query的输出目录
OutputDirBase=D:/workspacejavaee/hrm-parent/hrm-systemmanage-parent/hrm-systemmanage-common/src/main/java
#设置作者
author=yaohuaipeng
#自定义包路径
parent=myllxy
#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///hrm_system
jdbc.user=root
jdbc.pwd=276689237abc
4.配置GenteratorCode.java
package myllxy;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.*;
/**
1. Created by CDHong on 2018/4/6.
*/
public class GenteratorCode {
public static void main(String[] args) throws InterruptedException {
//用来获取Mybatis-Plus.properties文件的配置信息
final ResourceBundle rb = ResourceBundle.getBundle("mybatisplus-config"); //不要加后缀
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(rb.getString("OutputDir"));
// 设置第二次生成会覆盖第一次的生成
gc.setFileOverride(true);
gc.setActiveRecord(true);// 开启 activeRecord 模式
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
gc.setAuthor(rb.getString("author"));
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert());
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername(rb.getString("jdbc.user"));
dsc.setPassword(rb.getString("jdbc.pwd"));
dsc.setUrl(rb.getString("jdbc.url"));
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setTablePrefix(new String[]{"t_"});// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[]{"t_systemdictionary", "t_systemdictionaryitem"}); // 需要生成的表
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(rb.getString("parent"));
pc.setController("web.controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setEntity("domain");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
this.setMap(map);
}
};
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// 调整 controller 生成目录演示
focList.add(new FileOutConfig("/templates/controller.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDir") + "/cn/myllxy/system/web/controller/" + tableInfo.getEntityName() + "Controller.java";
}
});
// 调整 query 生成目录演示
focList.add(new FileOutConfig("/templates/query.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase") + "/cn/myllxy/system/query/" + tableInfo.getEntityName() + "Query.java";
}
});
// 调整 domain 生成目录演示
focList.add(new FileOutConfig("/templates/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase") + "/cn/myllxy/system/domain/" + tableInfo.getEntityName() + ".java";
}
});
// 调整 xml 生成目录演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirXml") + "/cn/myllxy/system/mapper" + tableInfo.getEntityName() + "Mapper.xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
TemplateConfig tc = new TemplateConfig();
tc.setService("/templates/service.java.vm");
tc.setServiceImpl("/templates/serviceImpl.java.vm");
tc.setEntity(null);
tc.setMapper("/templates/mapper.java.vm");
tc.setController(null);
tc.setXml(null);
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
}
}
system-server系统管理微服务搭建
1.导包
- hrm-systemmanage-common:需要其中的domain和query
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>myllxy</groupId>
<artifactId>hrm-systemmanage-common</artifactId>
</dependency>
</dependencies>
2.配置application.yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1010/eureka/ #注册中心服务端的注册地址
instance:
prefer-ip-address: true #使用ip进行注册
instance-id: system-server:2010 #服务注册到注册中心的id
server:
port: 2010
#应用的名字
spring:
application:
name: system-server
#集成DataSource
datasource:
username: root
password: 276689237abc
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///hrm-system
type: com.alibaba.druid.pool.DruidDataSource
#集成Mybatis-plus
mybatis-plus:
mapper-locations: classpath:cn/myllxy/system/mapper/*.xml
3.集成到配置中心,将配置文件放到configfiles中
spring:
cloud:
config:
uri: http://localhost:1030
name: application-system
profile: dev
4.配置主启动类
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("cn.myllxy.system.mapper")
public class SystemServerApplication2010 {
public static void main(String[] args) {
SpringApplication.run(SystemServerApplication2010.class);
}
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
Zuul配置路由
1.配置application.yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1010/eureka/ #注册中心服务端的注册地址
instance:
prefer-ip-address: true #使用ip进行注册
instance-id: zuul-server:1020 #服务注册到注册中心的id
server:
port: 1020
#应用的名字
spring:
application:
name: zuul-server
zuul:
# prefix: "/hrm"
ignored-services: "*" #禁止浏览器 使用服务名的方式去访问目标服务
routes:
system-server: "/system/**"
host: #zuul主机超时
connect-timeout-millis: 30000 #HTTP连接超时要比Hystrix的大
socket-timeout-millis: 30000 #socket超时
ribbon: #ribbon超时
ReadTimeout: 30000
ConnectTimeout: 30000
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 40000
2.将本地配置文件交给hrm-config-server管理
将配置文件提交到远程仓库,hrm-config-server配置码云账号地址密码等,hrm-gateway-zuul的application.yml中写要拿什么配置文件
system-server系统管理微服务集成swagger
1.导包
在有controller的模块中导包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.配置Swagger2
package cn.myllxy.system.config;
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 Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//对外暴露服务的包,以controller的方式暴露,所以就是controller的包.
.apis(RequestHandlerSelectors.basePackage("cn.myllxy.system.web.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("系统管理服务")
.description("平台服务接口文档说明")
.contact(new Contact("yhptest", "", "yhp@itsource.cn"))
.version("1.0")
.build();
}
}
Zuul集成swagger
在zuul中统一的配置swagger,去整合其他微服务的swagger。
由于zuul中没有controller,所以它只起到一个整合swagger。
1.导包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
2.配置SwaggerConfig与DocumentationConfig
package myllxy.config;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
//用来整合每个微服务的swagger
@Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
//一个swagger就对应一个微服务
//name代表服务名,location代表/zuul前缀/服务的访问路径/v2/api-docs,version代表版本
resources.add(swaggerResource("系统管理", "/system/v2/api-docs", "2.0"));
return resources;
}
private SwaggerResource swaggerResource(String name, String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}
package myllxy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("分布式人力资源综合平台")
.description("分布式人力资源综合平台接口文档说明")
.termsOfServiceUrl("http://localhost:1020")//zuul的地址
.contact(new Contact("yphtest", "", "yhp@itsoruce.cn"))
.version("1.0")
.build();
}
}
搭建课程微服务
1.创建hrm-course-common和hrm-course-server-2020模块
2.完成剩余工作
- 导包:拷贝hrm-systemmanage-service-2010的依赖,再改一点就行
- 注册到注册中心
- 集成配置中心客户端
- 集成Mybatis-Plus
- 集成swagger
- 配置主启动类
Zuul整合课程微服务
1.修改application-zuul-dev.yml
新增路由:
zuul:
# prefix: "/hrm"
ignored-services: "*" #禁止浏览器 使用服务名的方式去访问目标服务
routes:
system-server: "/system/**"
course-server: "/course/**"
2.swagger修改DocumentationConfig
@Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
//一个swagger就对应一个微服务
//name代表服务名,location代表/zuul前缀/服务的访问路径/v2/api-docs,version代表版本
resources.add(swaggerResource("系统管理", "/system/v2/api-docs", "2.0"));
resources.add(swaggerResource("课程管理", "/course/v2/api-docs", "2.0"));
return resources;
}