SpringBoot 笔记
创建SpringBoot工程方式一(Idea联网创建)方式二(使用官网创建)方式三(阿里云)方式四(手工制作)隐藏指定文件/文件夹进行文件内容对比SpringBoot概述parentstarter引导类内嵌tomcat三款常用服务器SpringBoot配置文件SpringBoot加载JUnit@SpringBootTest异常处理临时属性设置配置文件分类程序打包运行多环境配置配置的优先级(越来越高
SpringBoot
SpringBoot
简介
SpringBoot是由Pivoal团队提供的全新的设计框架,其设计的目的是用来简化Spring应用的初始搭建以及开发过程
创建SpringBoot工程
如果没有创建项目的先创建一个Empty Project即可
方式一(Idea联网创建)
点击Finish即可进入项目内
走到这使用方式一的项目就已经是创建完成!!
方式二(使用官网创建)
官网访问链接:SpringBoot官网
配置与我们所在Idea中所看的很相似所以这里就不多说
下载完成后,是一个.zip的压缩包,打开一看于刚刚在idea中创建的也不能说相似,简直是一模一样(其实idea就是使用此连接帮我们创建的,只是idea帮我们顺便把Module导入项目了)
方式三(阿里云)
要比官网镜像快很多
链接:https://start.aliyun.com/
但是版本比官网低很多
方式四(手工制作)
创建Maven项目
输入对应的Module名字
进入后先调好自己的Maven工程所存放位置,然后进行编写Maven文件:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
</parent>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
新建Application于com.test包下:
Application内的内容为:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
编写controller类进行测试是否可以运行,最终运行成功
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping
public String getAll(){
System.out.println("getBooks..");
return "getBooks";
}
}
隐藏指定文件/文件夹
进行文件内容对比
选中两个文件或多个文件
右键compare Files进行对比,可以看出
可通过圈中部分进行调高亮显示
SpringBoot概述
parent
- 所有SpringBoot项目要继承的项目,定义若干个坐标版本号(依赖管理,而非依赖),以达到减少依赖冲突的目的
- spring-boot-starter-parent各版本间存在着诸多坐标版本不同
- 开发SpringBoot程序要继承spring-boot-starter-parent
- spring-boot-starter-parent中定义了若干个依赖管理
- 继承parent模块可以避免多个依赖使用相同技术时出现依赖版本冲突
- 继承parent的形式也可以采用引入依赖的形式实现效果
starter
- SpringBoot中常见项目名称,定义当前项目使用所有依赖坐标,以达到减少依赖配置的目的
实际开发:
- 使用任意i坐标时,仅书写GAV中的G和A,V由SpringBoot提供,除非SpringBoot来提供对应版本V
- 如发送坐标错误,再指定Version(要小心版本冲突)
引导类
- 启动方式
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
内嵌tomcat
内嵌Tomcat工作原理是将Tomcat服务器作为对象运行,并将对象交给Spring容器管理
- 使用maven依赖管理变更起步依赖项
使用其他服务器的步骤(去除掉内置服务器,添加上新的服务器)
- Jetty比Tomcat更轻量级,可扩展性更强(相较于Tomcat),谷歌应用引擎(GAE)已经全面切换为Jetty
三款常用服务器
- tomcat(默认)apache出品,粉丝多,应用面广,负载了若干较重的组件
- jetty 更轻量级,负载性能远不及tomcat
- undertow undertow,负载性能勉强能跑赢tomcat
SpringBoot配置文件
SpringBoot加载JUnit
@SpringBootTest
- 名称:@SpringBootTest
- 类型:测试类注解
- 位置:测试类定义上方
- 作用:设置Junit加载的SpringBoot启动类
- 范例:
@SpringBootTest class SpringbootTest{}
- 相关属性:classes:设置SpringBoot启动类
注意事项:
如果测试类在SpringBoot启动类的包或子包中,可以省略启动类的设置,也就是省略classes的设定
异常处理
临时属性设置
- 带属性数启动SpringBoot
java -jar springboot.jar –server.port=80
- 带属性启动SpringBoot程序,为程序添加运行属性
配置文件分类
携带多个属性启动SpringBoot,属性间使用空格分隔
-
SpringBoot中4级配置文件
1级:file:config/application.yml 最高
2级:file:application.yml
3级:classpath:config/application.yml
4级:classpath:application.yml 最低 -
作用
1级与2级留作系统打包后设置通用属性,1级常用于运维经理进行线上整体项目部署方案调控,2级服务于运维人员配置涉密线上环境
3级与4级用于系统开发阶段设置通用属性,3级常用于项目经理进行整体项目属性调控,4级服务于开发人员开发与测试 -
多层级配置文件间的属性采用叠加并覆盖的形式作用于程序
一个参数多个匹配路径,如果优先级相同运行最后的配置
程序打包运行
多环境配置
配置的优先级(越来越高)
一个配置文件
多环境开发独立配置文件书写技巧(一)
application.yml中配置中的文件配置:
spring:
profiles:
active: test
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_db
username: root
password: admin
type: com.alibaba.druid.pool.DruidDataSource
application-dev.yml配置开发时的配置:
server:
port: 8081
application-pro.yml配置生产时的配置:
server:
port: 8080
application-test.yml配置测试时的配置:
server:
port: 8082
application.properties配置文件与application.yml相似,不过内容写法不一致
多环境开发独立配置文件书写技巧(二)
根据功能配置文件中的信息进行拆分,并制作成独立的配置文件,命名规则如下
- application-devDB.yml
- application-devRedis.yml
- application-devMVC.yml
使用include属性在激活指定环境的情况下,同时对多个环境进行加载使其生效,多个环境间使用逗号分隔
执行顺序 devDB,devMVC,dev
spring:
profiles:
active: dev
include: devDB,devMVC
当主环境dev与其他环境有相同属性时,主环境属性生效;其他环境中有相同属性时,最后加载的环境属性生效
在SpringBoot2.4开始使用group属性代替include属性,降低了配置书写量
使用group属性定义多种主环境与子环境的包含关系
执行顺序 dev,devDB,devMVC
spring:
profiles:
active: dev
group:
"dev": devDB,devMVC
"pro": proDB,proMVC
Maven与SpringBoot多环境兼容
- maven中设置多环境属性
<profiles>
<profile>
<id>env_dev</id>
<properties>
<profile.active>dev</profile.active>
</properties>
</profile>
<profile>
<id>env_pro</id>
<properties>
<profile.active>pro</profile.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
- SpringBoot中引用Maven属性
spring:
profiles:
active: @profile.active@
group:
"dev": devDB,devMVC
"pro": proDB,proMVC
- 执行Maven打包指令,并在生成的boot打包文件.jar文件中查看对应信息
当Maven与SpringBoot同时对多环境进行控制时,以Maven为主,SpringBoot使用@…@占位符读取Maven对应的配置属性值
开发实战
热部署
- 开启开发者工具
<!--启动热部署工具-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
-
激活热部署:Ctrl + F9
-
关于热部署
重启(Restart):自定义开发代码,包含类、页面、配置文件等,加载位置restart类加载器
重载(ReLoad):jar包,加载位置base类加载器
开启自动热部署
热部署范围配置
在appliation.yml配置文件下
默认不触发重启的目录列表
- /META-INF/maven
- /META-INF/resources
- /resources
- /static
- /public
- /templates
devtools:
restart:
# 设置不参与热部署的文件或文件夹
exclude: static/**,public/**,config/application.yml
# enabled: false 关闭热部署
关闭热部署
devtools:
restart:
# 设置不参与热部署的文件或文件夹
exclude: static/**,public/**,config/application.yml
enabled: false # 关闭热部署
使用优先级更高的进行配置关闭热部署
@SpringBootApplication
public class SSMPApplication {
public static void main(String[] args) {
//关闭热部署
System.setProperty("spring.devtools.restart.enabled","false");
SpringApplication.run(SSMPApplication.class);
}
}
配置高级
@ConfigurationProperties
-
使用@ConfigurationProperties为bean绑定属性
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data @Component @ConfigurationProperties(prefix = "servers") public class ServerConfig { private String ipAddress; private Integer port; private long timeout; }
servers: ipAddress: 195.168.1.0 port: 2345 timeout: -1
-
使用@ConfigurationProperties为第三方bean绑定属性
@Bean @ConfigurationProperties(prefix = "datasource") public DruidDataSource dataSource() { DruidDataSource ds = new DruidDataSource(); return ds; }
datasource: driverClassName: com.mysql.jdbc.Driver123
@EnableConfigurationProperties
-
使用@EnableConfigurationProperties注解可以将使用@ConfigurationProperties注解对应的类加入Spring容器
@SpringBootApplication @EnableConfigurationProperties(ServerConfig.class) public class Springboot13ConfiigurationApplication { }
@Data //@Component @ConfigurationProperties(prefix = "servers") public class ServerConfig { }
宽松绑定 / 松散绑定
都可以被识别
@Data
@ConfigurationProperties(prefix = "servers")
public class ServerConfig {
private String ipAddress;
private Integer port;
private long timeout;
}
- @ConfigurationProperties绑定属性支持属性名宽松绑定
@Data
@ConfigurationProperties(prefix = "servers")
public class ServerConfig {
private String ipAddress;
private Integer port;
private long timeout;
}
- 驼峰模式
ipAddress: 192.168.1.0
- 下划线模式
ip_address: 192.168.1.0
- 中划线模式
ip-address: 192.168.1.0
- 常量模式
IP_ADDRESS: 192.168.1.0
-
宽松绑定不支持注解@Value引用单个属性的方式
-
绑定前缀命名规范:仅能使用纯小写字母、数字、下划线作为合法的字符
常用计量单位绑定
@Data
@ConfigurationProperties(prefix = "servers")
public class ServerConfig {
private String ipAddress;
private Integer port;
private long timeout;
@DurationUnit(ChronoUnit.HOURS)
private Duration serverTimeOut;
// @DataSizeUnit(DataUnit.MEGABYTES)
private DataSize dataSize;
}
数据校验
- 添加JSR303规范坐标与Hibernate校验框架对应坐标
<!--1. 导入JSR303规范-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<!--使用Hibernate框架提供的校验器做实现类-->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
- 对Bean开启校验功能(@Validated)
@Data
//@Component
@ConfigurationProperties(prefix = "servers")
//2.开启对当前bean的属性注入校验,对ServerConfig中的字段进行校验
@Validated
public class ServerConfig {
}
- 设置校验规则
@Data
//@Component
@ConfigurationProperties(prefix = "servers")
//2.开启对当前bean的属性注入校验,对ServerConfig中的字段进行校验
@Validated
public class ServerConfig {
private String ipAddress;
//3.设置具体的规则
@Max(value = 8888,message = "最大值不能超过8888")
@Min(value = 202,message = "最小值不能低于202")
private Integer port;
private long timeout;
@DurationUnit(ChronoUnit.HOURS)
private Duration serverTimeOut;
// @DataSizeUnit(DataUnit.MEGABYTES)
private DataSize dataSize;
}
yml语法规则
可能会导致识别出错(把十进制转为八进制)
注意yaml文件中对于数字的定义支持进制书写格式,如需使用字符串请使用引号明确标注
加载测试专用属性
- 在启动测试环境时可以通过properties参数设置测试环境专用的属性
@SpringBootTest
@Import({MsgConfig.class})
public class ConfigurationTest {
@Autowired
private String msg;
@Test
public void testConfig() {
System.out.println(msg);
}
}
-
使用@Import注解加载当前测试类专用的配置
-
优势:比多开发中的测试环境影响范围更小,仅对当前测试类有效
-
在启动测试环境时可以通过args参数设置测试环境专用的传入参数,如果既有args,又有配置文件时,命令行(args)的优先级会比较高,同理在既有properties,也有配置文件的目录下时,properties的优先级会更高些,但是在既有args,properties,又有配置文件属性时,显示出properties,(好像不太合理噢?是不是想在main函数下时args设置的值时要比properties高的,确实是这样,但是在回忆一下官网,参考下图11~12)
@SpringBootTest(args = {"--datasource.driverClassName=2222"})
//@SpringBootTest(properties = {"datasource.driverClassName=223"})
class Springboot13ConfiigurationApplicationTests {
@Value("${datasource.driverClassName}")
private String port;
@Test
void contextLoads() {
System.out.println(port);
}
}
web环境模拟测试
- 模拟端口
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BookControllerTest {
@Test
void testRandomPort() {
}
}
- 虚拟请求测试
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class BookControllerTest {
@Test
void testRandomPort() {
}
}
如果匹配不一致会出现,类似此错误
-
虚拟请求状态匹配
@Test void testStatus(@Autowired MockMvc mvc) throws Exception { // http://localhost:8080/books // 创建虚拟请求,当前访问路径/books MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books"); // 执行对应的请求 ResultActions actions = mvc.perform(builder); //设定预期值与真实值进行比较,成功测试通过,失败测试失败 //定义本次调用的预期值 StatusResultMatchers status = MockMvcResultMatchers.status(); //预计本次调用时成功的:状态200 ResultMatcher ok = status.isOk(); //添加预计值到本次调用过程中进行匹配 actions.andExpect(ok); }
-
虚拟请求头匹配
@Test void testBody(@Autowired MockMvc mvc) throws Exception { // http://localhost:8080/books // 创建虚拟请求,当前访问路径/books MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books"); // 执行对应的请求 ResultActions actions = mvc.perform(builder); //设定预期值与真实值进行比较,成功测试通过,失败测试失败 //定义本次调用的预期值 ContentResultMatchers content = MockMvcResultMatchers.content(); //预计本次调用成功时返回getBooks ResultMatcher re = content.string("getBooks"); //添加预计值到本次调用过程中进行匹配 actions.andExpect(re); }
数据层测试事务回滚
-
为测试用例添加事务,SpringBoot会对测试用例对应的事务提交操作进行回滚
@SpringBootTest //添加事务 @Transactional public class DaoTest { }
-
如果在测试用例中提交事务,可以通过@Rollback注解设置
@SpringBootTest //添加事务 @Transactional @Rollback(false) public class DaoTest { }
测试用例数据设定
- 测试用例数据通常采用随机值进行测试,使用SpringBoot提供的随机数为其赋值
testcase:
book:
id: ${random.int} # random.int(10) 10以内的正整数 , random.int(5, 10) 5-10之间饿正整数
name: ${random.value}
uuid: ${random.uuid}
publishTime: ${random.long}
- ${random.int}表示随机整数
- ${random.int(10)}表示10以内的随机数
- ${random.int(10, 20)}表示10~20的随机数
- 其中()可以是任何字符,例如[], !! 均可以
数据源
数据源配置
- SpringBoot提供了三种内嵌的数据源对象供开发者选择
HikariCP:默认内置数据源对象
Tomcat提供DataSource:Hikari不可用的情况系下,且在web环境中,将使用tomcat服务器配置的数据源对象
Commons DBCP:Hikari不可用,tomca数据源也不可用,将使用dbcp数据源
默认HikariCP数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_db?serverTimezone=UTC
username: root
password: 123456
- 通用配置无法设置具体的数据源配置信息,仅提供基本的连接相关配置,如需配置,在下一级配置中设置具体设定
数据层解决方法
- 内置持久化解决方法——jdbcTemplate
配置:
依赖:
内嵌数据库
- SpringBoot提供了3种内嵌数据库开发者选择,提供测试效率
H2
HSQL
Derby
设置当前项目为web工程,并配置H2管理控制台参数
server:
port: 80
spring:
h2:
console:
path: /h2
enabled: true
- 访问用户名sa,默认密码123456
操作数据库
设置访问数据源
server:
port: 80
spring:
h2:
console:
path: /h2
enabled: true
# 初始化配置使用
datasource:
url: jdbc:h2:~/test
hikari:
driver-class-name: org.h2.Driver
username: sa
password: 123456
- H2数据库控制台仅用于开发阶段,线上项目请务必关闭控制台功能
server:
port: 80
spring:
h2:
console:
path: /h2
enabled: false
数据库设定
- SpringBoot可以根据url地址自动识别数据库种类,在保障驱动类存在的情况下,可以省略配置
server:
port: 80
spring:
h2:
console:
path: /h2
enabled: true
# 初始化配置使用
datasource:
url: jdbc:h2:~/test
hikari:
# driver-class-name: org.h2.Driver
username: sa
password: 123456
H2多用于测试,不适合上线
NoSQL
Redis
-
Redis是一款key-value存储结构的内存级NoSQL数据库
支持多种数据存储格式
支持持久化
支持集群 -
Redis下载(Windows版)
Redis下载及安装教程 -
Redis安装与启动(Windows版)
Windows解压安装或一键式安装
服务端启动命令
redis-server.exe redis.windows.conf
客户端启动命令
redis-cil.exe
Redis命令操作
清空数据库
使用idea书写springboot整合Redis
- 导入SpringBoot整合Redis坐标
- 配置Redis(采用默认配置)
spring:
redis:
host: localhost # 127.0.0.1
port: 6379
主机:localhost(默认)
端口:6379(默认)
- RedisTemplate提供操作各种数据存储类型的接口API
客户端:RedisTemplate
客户端:RedisTemplate以对象作为key和value,内部对数据进行序列化
set与get
hset与hget
StringRedisTemplate(常用)
客户端:StringRedisTemplate以字符串作为key和value,与Redis客户端操作等效
set与get
配置客户端
默认为lettucs
spring:
redis:
host: localhost # 127.0.0.1
port: 6379
client-type: lettuce
jedis
配置客户端专用属性
spring:
redis:
host: localhost # 127.0.0.1
port: 6379
client-type: jedis
lettuce:
pool:
max-active: 16
jedis:
pool:
max-active: 16
lettucs与jedis区别
- jedis连接Redis服务器是直连模式,当多线程模式下使用jedis会存在线程安全问题,解决方案可以通过配置连接池使每个连接专有,这样整体性能就大受影响
- lettucs基于Netty框架进行与Redis服务器连接,底层设计中采用StatefulRedisConnection。 StatefulRedisConnection自身是线程安全的,可以保障并发访问安全问题,所以一个连接可以被多线程复用。当然lettucs也支持多连接实例一起工作
Mongodb
MongoDB是一个开源、高性能、无模式的文档型数据库。NoSQL数据库产品中的一种,是最像关系型数据库的非关系型数据库
永久性存储与临时性存储相结合、修改频率高
- windows版Mongo下载
- windows版Mongo安装
- windows版Mongo启动
服务器启动
mongod.exe --dbpath=…\data\db
客户端启动
mongo --host=127.0.0.1 --port=27017
新增
db.集合名称.insert/save/insertOne(文档)
修改
db.集合名称.remove(条件)
删除
db.集合名称.update(条件,{操作种类:{文档} } )
查询(find)
整合
- 导包
- 配置客户端
- 客户端读写Mongodb
Elasticsearch(ES)
(不涉及太多)
ES是一个分布式全文搜索引擎
索引(主键 -> 数据)
倒排索引(数据 -> 主键 -> 数据)
缓存
Springboot提供了缓存技术,方便缓存使用
缓存使用(默认缓存供应商simple)
- 导入缓存技术对应的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
- 启用缓存
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
//开启缓存功能
@EnableCaching
public class Springboot19CatchApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot19CatchApplication.class, args);
}
}
- 设置进入缓存的数据
- 设置读取缓存的数据
- 设置当前操作的结束数据进入缓存
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.dao.BookDao;
import com.test.domain.Book;
import com.test.service.BookService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class BookServiceImpl extends ServiceImpl<BookDao, Book> implements BookService{
@Override
@Cacheable(value = "cacheSpace", key = "#id")
public Book getById(Integer id) {
return super.getById(id);
}
}
更换缓存供应商:Ehcache
- 加入Ehcache坐标(缓存供应商实现)
<!--使用ehcache加载缓存-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
- 缓存设定为使用Ehcache
spring:
cache:
type: ehcache
ehcache:
config: ehcache.xml
- 加入Encache配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径
-->
<diskStore path="D:\ehcache" />
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="60"
timeToLiveSeconds="60"
memoryStoreEvictionPolicy="LRU" />
<!-- timeToIdleSeconds="10"
timeToLiveSeconds="10"设置验证码十秒后过期-->
<cache
name="smsCode"
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="10"
timeToLiveSeconds="10"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
更换缓存供应商:Redis
- 加入Redis坐标(缓存供应商实现)
<!--使用redis加载缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置Redis服务器,缓存设定为使用Redis
spring:
cache:
type: redis
redis:
host: localhost
port: 6379
- 设置Redis相关配置
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_db?serverTimezone=UTC
username: root
password: 123456
cache:
type: redis
redis:
use-key-prefix: false # 是否使用前缀 默认true
cache-null-values: false # 是否缓存空值
key-prefix: sms_ # 指定前缀
time-to-live: 10s
redis:
host: localhost
port: 6379
知识补充:影响数据淘汰的相关配置(LRU、LFU)
更换缓存供应商:memcached
(SpringBoot中没有自带,需要硬编码)
SpringBoot未未提供对memcached的整合,需要使用硬编码方式实现客户端初始化管理
-
加入Xmemcached坐标(缓存供应商实现)
-
配置memcached服务器必要属性
-
创建读取属性配置信息类,加载配置
-
创建客户端配置类
-
配置memcaches属性
更换缓存供应商:jetcache
jetCache对SpringCache进行了封装,在原有功能的基础上实现了多级缓存、缓存统计、自动刷新、异步调用、数据报表等功能
- jetCache设定了本地缓存与远程缓存的多级缓存解决方案
本地缓存(local)
LinkedHashMap
Caffeine
远程缓存(remote)
Redis
Tair
步骤
- 加入jetcache坐标
- 配置远程缓存必须属性
配置规范
-
开启jetcache注解支持
-
声明缓存对象
-
操作缓存
-
启用方法注解
-
使用方法注解操作缓存
-
缓存对象必须保障可序列化
-
查看缓存统计报告
更换缓存供应商:j2cache
- j2cache是一个缓存整合框架,可以提供缓存的整合方案,使各种缓存搭配使用,自身不是提供缓存功能
- 基于 ehcache + redis 进行整合
步骤
- 加入j2cahce坐标,加入整合缓存的坐标
- 配置使用j2cache(application.yml)
- 配置一级缓存与二级缓存以及一级缓存数据到二级缓存的发送方式(j2cache.propertise)
- 设置使用缓存
定时器
Quartz相关概念:
- 工作(job):用于定义具体执行的工作
- 工作明细(jobDetail):用于描述定时工作相关的信息
- 触发器(Trigger):用于描述触发工作的规则,通常使用cron表达式定义调度规则
- 调度器(Scheduler):描述了工作明细与触发器的对应关系
步骤
原始定时器
import java.util.Timer;
import java.util.TimerTask;
/**
* @author : zxx
* @date : 2022/9/13 11:01
*/
public class TimerTaskTest {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("timer task run...");
}
};
timer.schedule(task,0,2000);
}
}
SpringBoot整合Quartz
-
导入SpringBoot整合quartz的坐标
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>
-
定义具体要执行的任务,继承QuartzjobBean
import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; /** * @author : zxx * @date : 2022/9/13 14:36 */ public class MyQuartz extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { System.out.println("quartz task run..."); } }
-
定义工作明细与触发器,并绑定对应关系
import com.test.quartz.MyQuartz; import org.quartz.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author : zxx * @date : 2022/9/13 11:02 */ //spring定时器配置 @Configuration public class QuartzConfig { @Bean public JobDetail printJobDetail() { //绑定具体的工作 ( storeDurably做持久化 ) return JobBuilder .newJob(MyQuartz.class) .storeDurably() .build(); } @Bean public Trigger printJobTrigger() { //任意月的任意天任意小时任意分钟0秒开始5秒执行一次 秒 分 小时 天 月 星期几(?代表与前面的日期匹配) ScheduleBuilder schedBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?"); //绑定对应的工作明细 return TriggerBuilder .newTrigger() .forJob(printJobDetail()) .withSchedule(schedBuilder) .build(); } }
开启Spring的定时器
-
开启定时任务功能
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication //开启定时任务功能 @EnableScheduling public class Springboot22TaskApplication { public static void main(String[] args) { SpringApplication.run(Springboot22TaskApplication.class, args); } }
-
设置定时执行的任务,并执行周期
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @author : zxx * @date : 2022/9/13 13:45 */ @Component public class MyBean { @Scheduled(cron = "0/1 * * * * ?") public void print() { System.out.println(Thread.currentThread().getName() + " : spring task run..."); } }
-
定时任务相关配置
SpringBoot整合JavaMail
- SMTP:简单邮件传输协议,用于发送电子邮件的传输协议
- POP3:用于接受电子邮件的标注协议
- IMAP:互联网消息协议,是POP3的替代协议
步骤
-
导入SpringBoot整合JavaMail的坐标
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
配置JavaMail
spring: mail: host: smtp.163.com username: **********@163.com password: ************
host:中需要写入所使用邮箱的(此处使用163为例)
usename:写入自己的邮箱
password:获取如下
常规设置
- 开启定时任务功能
SendMailService 接口
/**
* @author : zxx
* @date : 2022/9/13 22:41
*/
public interface SendMailService {
void sendMail();
}
实现类(发送简单邮件)
import com.test.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
/**
* @author : zxx
* @date : 2022/9/13 22:41
*/
@Service
public class SendMailServiceImpl implements SendMailService {
@Autowired
private JavaMailSender javaMailSender;
//发送人
private String from = "**********@163.com";
//接收人
private String to = "**********@qq.com";
//标题
private String subject = "测试邮件";
//正文
private String context = "测试邮件的正式内容";
@Override
public void sendMail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from+"(小甜甜)");
message.setTo(to);
message.setSubject(subject);
message.setText(context);
javaMailSender.send(message);
}
}
实现类(发送复杂邮件)
/**
* @author : zxx
* @date : 2022/9/13 16:11
*/
@Service
public class SendMailServiceImpl2 implements SendMailService {
@Autowired
private JavaMailSender javaMailSender;
//发送人
private String from = "**********@163.com";
//接收人
private String to = "**********@qq.com";
//标题
private String subject = "测试邮件";
//正文
private String context = "<img src='https://img.tt98.com/d/file/96kaifa/2019052219083938/002.jpg'/>" +
"<br><a href='https://www.baidu.com'>点开有惊喜</a>";
@Override
public void sendMail() {
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true); //是否允许挂附件
helper.setFrom(from+"(小甜甜)");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(context, true); //是否为html
//添加附件
File file1 = new File("D:\\壁纸\\admin_picture.jpg");
File file2 = new File("E:\\Java_code\\springboot_test\\springboot_23_mail\\target\\springboot_23_mail-0.0.1-SNAPSHOT.jar");
helper.addAttachment("头像头像不要羡慕.jpg",file1);
helper.addAttachment(file2.getName(),file2);
javaMailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
消息
企业级应用中广泛使用的三种异步消息传递技术
- JMS
- AMQP
- MQTT
JMS(是一种规范)
pubsub、BytesMessage
AMQP(是一种协议)
direct exchange、topic exchange
AMQP消息种类:byte[]
MQTT(消息队列遥测传输)
Kafka
- Kafka,一种高吞吐量的分布式发布订阅消息系统,提供实时消息功能
消息处理主流框架
RabbitMQ
RabbitMQ安装
启动
SpringBoot配置RabbitMQ步骤
-
导入SpringBoot整合RabbitMQ坐标
-
配置RabbitMQ(采用默认配置)
direct书写
-
定义消息队列(direct)
-
生成与消费消息(direct)
-
使用消息监听器对消息队列监听(direct)
-
使用多消息监听器对消息队列监听进行消息轮循处理(direct)
topic书写
- 定义消息队列(topic)
绑定键匹配规则
-
* (星号):用来表示一个单词,且该单词是必须出现的
-
# (井号):用来表示任意数量
-
生产与消费消息(topic)
-
使用消息监听器对消息队列监听(topic)
RocketMQ
Kafka
启动zookeeper、kafka
创建topic、查看topic、删除topic
生产者功能测试、消费者功能测试
SpringBoot整合Kafka
-
导入SpringBoot整合Kafka坐标
-
配置Kafka(采用默认配置)
-
生产消息
-
使用消息监听器对消息队列监听
监控
监控的意义
- 监控服务状态是否宕机
- 监控服务运行指标(内存、虚拟机、线程、请求等)
- 监控日志
- 管理服务(服务下线)
监控原理
- Actuator提供了SpringBoot生产就绪功能,通过端点的配置与访问,获取端点信息
- 端点描述了一组监控信息,SpringBoot提供了多个内置端点,也可以根据需要自定义端点信息
- 访问当前应用所有端点信息:
/actuator
- 访问端点详细信息:
/actuator/端点名称
暴漏端点功能
- 端点中包含的信息存在敏感信息,需要对外暴漏端点功能时手动设定指定端点信息
监控的实施方式
- 显示监控信息的服务器:用于获取服务信息,并显示对应的信息
- 运行的服务:启动时主动上报,告知监控服务器自己需要受到监控
可视化监控平台
- Spring Boot Admin,开源社区项目,用于管理和监控SpringBoot应用程序。客户端注册到服务端后,通过HTTP请求方式,服务端定期从客户端获取对应的信息,并通过UI界面展示对应的i信息
步骤
Admin服务端
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.7.4</version>
</dependency>
-
配置
server: port: 8080
-
设置启动Spring-Admin
import de.codecentric.boot.admin.server.config.EnableAdminServer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableAdminServer public class Springboot25AdminServerApplication { public static void main(String[] args) { SpringApplication.run(Springboot25AdminServerApplication.class, args); } }
Admin客户端
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.7.4</version>
</dependency>
-
配置
server: port: 80 spring: boot: admin: client: url: http://localhost:8080 # 开放健康信息 management: endpoint: health: show-details: always # 打开所有项 endpoints: web: exposure: include: "*"
Info端点指标控制(自定义监控指标)
-
为info端点添加自定义指标(yml)
info: appName: @project.artifactId@ version: @project.version@ company: zxx author: zxx
-
为info端点添加自定义指标(Java)
更多推荐
所有评论(0)