Java_Configration File
:如题:从此让你摆脱配置繁琐的烦恼
日志配置
logback
日志核心配置文件 Logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<property name="LOG_HOME" value="/home" />
<!--控制台日志, 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度,%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!--文件日志, 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<!--日志文件最大的大小-->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- show parameters for hibernate sql 专为 Hibernate 定制 -->
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" />
<logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" />
<logger name="org.hibernate.SQL" level="DEBUG" />
<logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />
<!--myibatis log configure-->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>
<!-- 日志输出级别 -->
<root level="DEBUG">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE"/>
</root>
</configuration>
Swagger3_Config
pom
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
application.yml
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
Swagger3_Config
- 访问连接如下:
- http://localhost:8080/swagger-ui/index.html
package com.example.spring_vue.configs;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
/*解决空指针
* Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
* 这是因为Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher。
* 该注解可以更改匹配规则。你也可以直接修改配置spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER来更改规则
* 但是这样仅仅是使其不抛异常,并不能实质性访问该页面Swagger
* 解决办法注入Bean如下
* @Bean
* public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor()
* 访问连接如下:
* http://localhost:8080/swagger-ui/index.html
* */
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
@Bean
public Docket docket(){
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.enable(true)
.groupName("ZRJ")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.spring_vue.controller"))
.paths(PathSelectors.any())
.build();
}
@SuppressWarnings("all")
public ApiInfo apiInfo(){
return new ApiInfo(
"zrj's api",
"redis project",
"v1.0",
"test@qq.com", //开发者团队的邮箱
"ZRJ",
"Apache 2.0", //许可证
"http://www.apache.org/licenses/LICENSE-2.0" //许可证链接
);
}
}
当然,如果希望回忆部分Swagger2的知识的话:
@Api注解可以用来标记当前Controller的功能。
@Api(tags = "projectcontroller接口",description = "项目工程的所有接口") //类的说明
@ApiOperation注解用来标记一个方法的作用。
@ApiOperation(value = "添加建筑工程",notes = "添加") //方法的说明
@ApiImplicitParam注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入。 @ApiImplicitParam(name = "建筑工程",value ="新增建筑工程实体类" ,dataType = "com.csoracle.cm.model.Project")
@ApiModel 标记实体类
@ApiModel("建筑工程类") //实体类说明
@ApiProperty 标记实体类属性
@ApiModelProperty(name = "pid",value = "工程pid")```
controller层主要注解
@Api(tags="APP用户注册Controller")
@ApiOperation(value="用户注册",notes="手机号、密码都是必输项,年龄随边填,但必须是数字")
springboot_mybatis
pom.xml
<java.version>1.8</java.version>
<mysql.version>8.0.25</mysql.version>
<druid.version>1.2.6</druid.version>
<mybatis.version>2.2.2</mybatis.version>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.xml
spring:
# DataBase Connection -- MyBatis -- MySql
datasource:
druid:
# serverTimezone可以设置为北京时间GMT%2B8、上海时间Asia/Shanghai或者香港时间Hongkong
url: jdbc:mysql://localhost:3306/zhibilin?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
username: root
password: Aa02606896098
min-idle: 3
max-active: 10
driver-class-name: com.mysql.cj.jdbc.Driver
login-timeout: 60000
# MyBatis 配置
mybatis:
# 配置全局配置 Xml 文件的文件路径(SpringBoot 配置 MyBatis 不需要添加这个全局配置文件了)
#config-location: classpath:mybatis/mybatis-config.xml
# 配置 Xml 文件路径(注意:文件在 resource 包中,不知道写在 java 包中可不可以)
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
# 开启驼峰命名(必备,因为没有配置实体类属性与数据库表字段的对应方式,同时实体类属性名必须按照驼峰规则命名)
map-underscore-to-camel-case: true
mybatis_plus 及其逆向工程
pom.xml
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--mybatis-plus 持久层-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
逆向工程——代码生成器
public class MPcodeGenerator {
// 处理 all 情况
protected static List<String> getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
public static void main(String[] args) {
String PROJECT_PATH = System.getProperty("user.dir"); //当前项目目录
String BASE_PATH = PROJECT_PATH + "/src/main/java/tech/zhibilin/templates";
// 六个文件的路径
String entityPath = BASE_PATH + "/entity";
String mapperPath = BASE_PATH + "/mapper";
String mapperXmlPath = PROJECT_PATH + "/src/main/resources/mapper";
String servicePath = BASE_PATH + "/service";
String serviceImplPath = BASE_PATH + "/service/impl";
String controllerPath = BASE_PATH + "/controller";
FastAutoGenerator
//数据源配置
.create(new DataSourceConfig
.Builder("jdbc:mysql://127.0.0.1:3306/atguigu_shang_rong_bao?serverTimezone=Asia/Shanghai",
"root",
"root")
.schema("atguigu_shang_rong_bao")
)// 全局配置
.globalConfig((scanner, builder) -> builder
.outputDir(PROJECT_PATH ) // 输出路径
.dateType(DateType.TIME_PACK)
// 作者名称
.author("admin")
// 开启覆盖已生成的文件
.fileOverride()
// 禁止打开输出目录
.disableOpenDir()
// 指定输出目录
// .outputDir(packagePath)
// 开启swagger2。注释掉则默认关闭。
.enableSwagger()
// 时间策略
.dateType(DateType.TIME_PACK)
// 时间格式
.commentDate("yyyy-MM-dd")
)
.packageConfig((scanner, builder) -> builder
// .parent(scanner.apply("请输入包名?"))
// 阶段1:各个文件的包名设置,用来拼接每个java文件的第一句:package com.XXX.XXX.XXX.xxx;
// 父包名配置
.parent(PROJECT_PATH)
.entity("entity")
.mapper("mapper")
.service("service")
.serviceImpl("service.impl")
.controller("controller")
// 阶段2:所有文件的生成路径配置
.pathInfo(
new HashMap<OutputFile, String>() {{
// 实体类的保存路径
put(OutputFile.entity, entityPath);
// mapper接口的保存路径
put(OutputFile.mapper, mapperPath);
// mapper.xml文件的保存路径
put(OutputFile.mapperXml, mapperXmlPath);
// service层接口的保存路径
put(OutputFile.service, servicePath);
// service层接口实现类的保存路径
put(OutputFile.serviceImpl, serviceImplPath);
// 控制类的保存路径
put(OutputFile.controller, controllerPath);
}}
)
)
// 数据库表配置
.strategyConfig((scanner, builder) -> builder
.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
.controllerBuilder()
.enableRestStyle()
.enableHyphenStyle()
.entityBuilder()
.enableLombok()
.naming(NamingStrategy.underline_to_camel)
.columnNaming(NamingStrategy.underline_to_camel)
.idType(IdType.AUTO)
.logicDeletePropertyName("isDeleted")
.versionPropertyName("version")
.addTableFills(
new Column("create_time", FieldFill.INSERT),
new Column("update_time", FieldFill.INSERT_UPDATE),
new Column("is_deleted", FieldFill.INSERT),
new Column("version", FieldFill.INSERT_UPDATE)
).build())
.templateEngine(new FreemarkerTemplateEngine())
// .templateConfig(config -> {
// config.entity("/templates/entity.java")
// .service("/templates/service.java")
// .serviceImpl("/templates/serviceImpl.java")
// .mapper("/templates/mapper.java")
// .mapperXml("/templates/mapper.xml")
// .controller("/templates/controller.java").build();
// })
.execute();
}
Spring-Cloud-alibaba
微服务:Greenwich.SR3
<spring-boot-parent.version>2.1.8.RELEASE</spring-boot-parent.version>
<spring-cloud-alibaba.version>2.1.0.RELEASE</spring-cloud-alibaba.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
<spring-cloud-openfeign.version>2.1.3.RELEASE</spring-cloud-openfeign.version>
<spring-cloud-gateway.version>2.1.3.RELEASE</spring-cloud-gateway.version>
依赖库
<!-- 微服务-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- api 网关-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>${spring-cloud-gateway.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 服务远程调用-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>${spring-cloud-openfeign.version}</version>
</dependency>
<!-- 微服务阿里巴巴-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 服务注册/发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>${spring-cloud-alibaba.version}</version>
</dependency>
<!-- 配置中心来做配置管理-->
<!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-starter-alibaba-nacos-config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>${spring-cloud-alibaba.version}</version>
</dependency>
</dependencies>
注册中心nacos
开启服务注册与发现
boostrap.yaml:
配置中心nacos
开启服务注册与发现
boostrap.yaml:同上
远程调用openfeign
开启远程调用指定远程调用包:@EnableFeignClients(basePackages =“com.atguigu.gulimall.member.feign”)
例如:远程服务1
调用远程服务一
网关gateway
向nacos注册发现本服务,
向nacos配置中心进行相关配置
引入gateway时该微服务不能存在springbootstart-web
application.yaml编写route规则
server:
port: 88
spring:
cloud:
gateway:
routes:
- id: test_route
uri: https://www.qq.com
predicates:
- Query=url,baidu
- id: test_route_qq
uri: https://www.qq.com
predicates:
- Query=url,qq