java_微服务02SpringBoot学习笔记

公司有个外包的项目,未来可能需要转为自研,把之前的java捡起来吧。
本笔记源于:Spring Boot 入门 - 目录:https://www.iteye.com/blog/rensanning-2355928

Spring Boot 入门 - 基础篇(1)- 创建工程

@SpringBootApplication = @Configuration + @ComponentScan + @EnableAutoConfiration
默认扫描的package是启动Application类所在的package

Spring Boot工程中如果有多个main()函数,需要指定启动类

1
2
3
4
<properties>   
<!-- The main class to start by executing java -jar -->
<start-class>com.rensanning.springboot.SpringBootDemoApplication</start-class>
</properties>

Spring Boot 入门 - 基础篇(2)- 嵌入式容器

刚才开始使用spring boot的开发者会有种很直观的感觉,servlet容器“不见了”。之前开发web项目,都是把程序写完后部署到servlet容器(比如Tomcat),但是使用spring boot开发项目,写完程序后直接就能运行了,觉得些许奇怪! 其实呢,这是因为Spring Boot中内嵌了Tomcat、Jetty和Undertow服务器。之所以开发者在默认情况下不需要做任何配置,是因为spring boot提供了一个名为EmbeddedServletContainerAutoConfiguration的配置类 (@Configuration注解的类),spring boot能实现“零配置”,是因为spring定义了好多这样的配置类(配置没有少,只是以前由开发者自己的工作交由spring完成了),这种情况下大多数开发人员将只需使用适当的“启动器”来获得一个完全配置的实例。spring-boot-starter-web默认使用嵌套式的Tomcat作为Web容器对外提供HTTP服务,默认端口8080对外监听和提供服务。但同样可以使用spring-boot-starter-jetty或者spring-boot-starter-undertow作为Web容器。

Spring Boot 入门 - 基础篇(3)- 日志管理

Spring Boot支持JUL,Log4J2和Logback。

默认设置

1
2
3
4
5
-采用SLF4J + Logback  
-日志只输出到控制台
-级别Level为INFO
-日志文件rotate大小为10Mb
-输出格式为:时间戳 级别 进程ID --- [线程名] 类名 日志内容

添加VM参数 -Dspring.profiles.active=dev,选择启用某一组配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
<configuration>   
<include resource="org/springframework/boot/logging/logback/base.xml" />
<springProfile name="dev,staging">
<logger name="com.rensanning.springboot" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE" />
</logger>
</springProfile>
<springProfile name="production">
<logger name="com.rensanning.springboot" level="WARN" additivity="false">
<appender-ref ref="FILE" />
</logger>
</springProfile>
</configuration>

Spring Boot 入门 - 基础篇(4)- 静态资源

(3)SpringBoot的请求响应
SpringBoot已经自动将「/static」「/public」「/resources」「/META-INF/resources」识别为资源文件夹。
引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Project Root  
└─src
└─ main
└─ resources
├─ static
| └─ css
| └─ a.css
├─ public
| └─ css
| └─ b.css
├─ resources
| └─ css
| └─ b.css
└─ META-INF
└─ resources
└─ css
└─ d.css

访问URL:

1
2
3
4
http://localhost:8080/css/a.css  
http://localhost:8080/css/b.css
http://localhost:8080/css/c.css
http://localhost:8080/css/d.css

详细配置:

1
src/main/resources/application.properties

引用

1
2
3
4
5
spring.resources.static-locations=classpath:/static/  
spring.resources.cache-period=604800
spring.resources.chain.gzipped=true
spring.resources.chain.cache=false
spring.resources.add-mappings=false

使用方法:
引用

1
2
3
4
5
6
7
8
──resources  
├─static
│ ├─css
│ │ index.css
│ └─js
│ index.js
└─templates
index.ftl

Spring Boot 入门 - 基础篇(5)- 使用WebJars

Spring Boot 入门 - 基础篇(6)- 页面模板

页面模板使用举例
Spring Boot支持很多模板引擎,但嵌入式容器JSP有限制,2010年后Velocity停止更新,所以这两个不建议使用。
(1)Thymeleaf
(2)FreeMarker

Spring Boot 入门 - 基础篇(7)- 国际化

Spring Boot 入门 - 基础篇(8)- 数据库操作

(1)导入mybatis-spring-boot-starter
(2)设置日志级别(Ajax,Java)

Spring Boot 入门 - 基础篇(9)- 文件上传下载

(1) 单文件上传
(2)多文件上传(Ajax,Java)
(3)上传文件大小限制
(4)文件下载(CSV/Excel/PDF)

Spring Boot 入门 - 基础篇(10)- 发送邮件

(1)配置
pom.xml
(2)文本邮件
(3)HTML邮件
(4)带附件邮件
(5)Template模板
Java代码
(6)国际化对应
(7)异步发送邮件
开启异步支持@EnableAsync

Spring Boot 入门 - 基础篇(11)- 数据源配置

(1)单一数据源
(2)多个数据源
数据源不局限于数据库:
多种数据库,比如:MySQL里的DB1、PostgreSQL的DB2、Oracle的DB3
一种数据库里的多个库,比如:MySQL里的DB1、DB2、DB3
(3)动态数据源
Spring提供org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource来支持DataSource路由配置,
具体可以参考官网Blog:https://spring.io/blog/2007/01/23/dynamic-datasource-routing/
a - 定义配置
b - 切换数据源
需要切换数据源的时候SchemaContextHolder.setSchemaType(SchemaType.MASTER);完成后调用clear()即可。
(4)基于package指定数据源
上边已经可以获取到多个Datasource,那么就可以通过DataSource生成不同的SqlSessionFactoryBean,通过@MapperScan为不同的package指定不同的SqlSessionFactoryBean。
(5)通过数据库管理数据源
上边场景基本都是所有数据库信息都已知,可在代码(或application.properties)中固定配置!还有一种很常见的场景是用户登录时使用一个数据源,但是登录后的数据源需要通过从DB中取得,需要能实时更新DataSource路由。可以通过自己实现AbstractDataSource来自己对数据源的创建和获取等管理操作。
具体参考附件代码:点击下载

Spring Boot 入门 - 基础篇(12)- 数据校验

(1)单字段校验
(2)自定义错误信息
(3)嵌套校验 @Valid
(4)组校验
定义Group
只校验Group1的字段
顺序执行校验
假如以下定义,如果name为空,两个错误提示都会显示到页面上。

1
2
3
@NotEmpty(message = "请输入姓名!")   
@Length(min = 1, max = 10, message = "1到10位字符")
private String name;

只有@NotEmpty不出错的情况下才执行@Length:

1
2
3
4
5
6
7
public interface First { }   
public interface Second { }

@GroupSequence({First.class, Second.class})
public interface All {

}

(5)多字段校验
实现Spring的Validator
(6)自定义校验
a - 已有注解基础上自定义
b - 单字段校验
c - 多字段关联校验

Spring Boot 入门 - 基础篇(13)- 异常处理

Spring Boot 入门 - 基础篇(14)- 参数设置

(1)读取优先顺序
a - 命令行参数 –key=value
b - JVM参数 -Dkey=value
c - 环境变量

1
2
d - application-{profile}.properties  
e - application.properties

(2)文件格式
同时支持properties或YAML。
变量可以嵌套使用
(3)文件位置

1
2
src/main/resources/config/application.properties  
src/main/resources/application.properties

也可以通过@PropertySource(“classpath:config.properties”) 来读入任意其他设置文件。
(4)多环境配置
通过设置参数“spring.profiles.active”即可切换设置文件。
(5)设置值的Key支持Relaxed binding
以下四种写法都是可以的。

1
2
3
4
person.firstName 标准骆驼式语法  
person.first-name 横线 多用于.properties 或 .yml
person.first_name 下划线 多用于.properties 或 .yml
PERSON_FIRST_NAME 大写 多用于环境变量

(6)读取配置值

1
2
3
4
5
6
7
8
9
10
a - @Value()  
@Value支持二元操作符并支持嵌套:
#{expression?:default value}
${property:default value}

b - @ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "prefix")

c – Environment

Spring Boot 入门 - 基础篇(15)- 工程部署

Spring Boot 入门 - 进阶篇(1)- Servlet、Filter、Listener、Interceptor

用户认证授权、日志记录MDC、编码解码、UA检查、多端对应等都需要通过拦截请求来共通处理,这时就需要Filter、Listener、Interceptor。而把非Spring Boot项目转换成Spring Boot项目需要沿用以前的这些代码,所以有必要了解这几个东西的用法。

通常来说,用户通过浏览器发起Request进入服务器后侧处理顺序如下:
Client -> Listener -> ServletContainer -> Filter -> Servlet -> Interceptor

1
2
3
(1)Servlet 2.5采用web.xml定义Servlet、Filter、Listener  
(2)Servlet 3.0开始不再需要web.xml,可以通过注解或Java代码定义Servlet/Filter等。
(3)Spring Boot也采用无web.xml,以Filter为例,添加方法如下:

1)通过@Component让Spring扫描到即可处理拦截处理所有请求
2)通过@Configuration + @Bean来管理未被扫描到的Filter
3)通过@Configuration + @Bean + FilterRegistrationBean更灵活的设置Filter
4)通过@ServletComponentScan自动扫描@WebServlet, @WebFilter, @WebListener

Spring Boot 入门 - 进阶篇(2)- 异步调用(@Async)

使用了@Async的方法,会被当成是一个子线程,所有整个sendSms方法,会在主线程执行完了之后执行
同一个类中,一个方法调用另外一个有@Async的方法,注解是不会生效的

Spring Boot 入门 - 进阶篇(3)- 定时任务(@Scheduled)

(1)开启定时任务功能
(2)定义定时任务
1)@Scheduled注解

1
2
3
@Scheduled(cron="*/5 * * * * MON-FRI")   
public void doSomeTask(){
}

2)实现SchedulingConfigurer
3)动态定义
(3)规则定义到配置文件

Spring Boot 入门 - 进阶篇(4)- REST访问(RestTemplate)

Spring Boot 入门 - 进阶篇(5)- 数据缓存(@Cacheable)

(1)添加 spring-boot-starter-cache 依赖
(2)开启缓存功能
(3)缓存数据
对于缓存的操作,主要有:@Cacheable、@CachePut、@CacheEvict。
(4)集成EhCache
(5)组合CacheManager
从多个CacheManager中轮询得到相应的Cache。
设置缓存无效化 spring.cache.type=none
缓存的对象必须实现Serializable
除GuavaCacheManager之外都支持Spring事务,即回滚时Cache的数据也会被移除

Spring Boot 入门 - 进阶篇(6)- 启动加载(CommandLineRunner)

Spring Boot 入门 - 进阶篇(7)- 自动配置(AutoConfigure)

Spring Boot 入门 - 进阶篇(8)- 应用监控(Actuator)

其他教程

SpringBoot入门及进阶:https://blog.csdn.net/dwhdome/article/details/83418817
SpringBoot入门教程:https://blog.csdn.net/huzecom/article/details/101191705
超详细的Spring Boot入门笔记:https://blog.csdn.net/rickiyeat/article/details/77543445
Spring Boot项目的内嵌容器:https://blog.csdn.net/weixin_33701617/article/details/860139

java spring系列
java_spring01读书要点
java_spring02ioc有什么优点
java_spring04Autowired与Resource差异解析
java_spring05循环依赖
java_spring06AOP
java_spring07mybatis学习要点
java_微服务01SpringCloud基础
java_微服务02SpringBoot学习笔记
java_微服务03SpringBoot常见问题
java_微服务04SpringCloud学习笔记
java_微服务06SpringCloud常见问题之Eureka
java_微服务07SpringCloud常见问题之Feign
java_微服务08SpringCloud常见问题之Hystrix
java_微服务09SpringCloud常见问题之Ribbon
java_微服务10SpringCloud常见问题之Zuul
java_微服务11SpringCloud其他问题

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×