Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

部分 I. Spring Boot

目录

1. Spring Boot Quick start
1.1. 创建项目
1.2. pom.xml
1.3. Controller
1.4. Springboot with Maven
1.4.1. resource
1.4.2. Maven run
1.4.3. Spring Boot maven 插件 build-image
1.4.4. 生成项目信息
2. Spring 开发环境
2.1. Java 开发环境
2.2. 安装 Spring Tool Suite
2.3. Dashboard
2.4. Spring Initializr - Bootstrap your application
3. SpringApplication
3.1. 运行 Spring boot 项目
3.1.1. Linux systemd
3.1.2. 传统 init.d 脚本
3.1.3. 编译用于Tomcat的 War
3.2. @SpringBootApplication
3.2.1. 排除 @EnableAutoConfiguration 加载项
3.3. 获取 Resources 目录中的静态文件
3.4. @EnableAutoConfiguration
3.5. @ComponentScan
3.6. @EntityScan 实体扫描
3.7. @EnableJpaRepositories
3.8. 启动和销毁
3.9. 打印环境变量
3.10. CharacterEncodingFilter
3.11. 隐藏 Banner
3.12. 实体与仓库扫描
3.13. 列出 Beans
3.14. Tomcat 端口
3.15. 配置项设定
3.16. spring.profiles.active
3.17. @Profile("dev") / @ActiveProfiles("dev")
3.18. 设置默认时区
4. 如何优雅停止 Springboot 运行
4.1. 准备工作
4.2. kill 命令演示
4.3. 容器中如何优雅关闭 Springboot
4.4. 写入PID文件
5. Properties 配置文件
5.1. application.properties 配置文件
5.1.1. application.properties 参考
5.1.2. 启动指定参数
5.1.3. 加载排除
5.1.4. PID FILE
5.1.5. banner 关闭
5.1.6. server
5.1.7. logging
5.1.8. 内嵌 tomcat server
5.1.9. servlet
5.1.10. JSON 输出与日期格式化
5.1.11. SMTP 相关配置
5.1.12. Redis
5.1.13. MongoDB
5.1.14. MySQL
5.1.15. Oracle
5.1.16. default_schema
5.1.17. datasource
5.1.18. velocity
5.1.19. Security 相关配置
5.1.20. MVC 配置
5.1.21. Kafka 相关配置
5.2. Properties 文件
5.2.1. @Value 注解
5.2.2. @EnableConfigurationProperties 引用自定义 *.properties 配置文件
5.2.3. @PropertySource 注解载入 properties 文件
5.3. Environment 读取配置文件
5.4. 手工载入 *.properties 文件
5.4.1. 家在 resources 目录中的指定文件
5.4.2. 从 InputStreamReader 打开 application.properties
5.5. 命令行注入配置项
5.5.1. spring.profiles.active 参数切换配置文件
5.5.2. SpringApplicationBuilder.properties() 方法添加配置项
5.5.3. 禁用命令行注入环境变量
5.6. PropertyResolver 获取配置
5.7. 参数引用
5.8. 默认值
5.9. 产生随机数
5.9.1. 随机数
5.10. 多行字符串
5.11. 注入多值属性 arrays, list, set
5.12. List 列表类型
5.13. Map类型
5.14. Binder
5.15. 加密 application.properties 中的敏感内容
6. Spring boot with Logging
6.1. 配置日志文件
6.1.1. 日志输出级别
6.1.2. Spring boot 2.1 以后的版本不打印 Mapped 日志问题
6.1.3. 禁止控制台输出日志
6.1.4. 定制日志格式
6.1.5. 彩色输出
6.2. 日志切割
6.3. 彩色日志
6.4. 打印日志
6.4.1. lombok
6.5. logback 配置详解
6.5.1. 标准输出
6.5.2. 禁止 logback 日志输出
6.5.3. 指定Class过滤日志
6.5.4. configuration 属性配置
6.5.5. contextName 设置上下文名称
6.5.6. property 设置变量
6.5.7. encoder 日志格式设置
6.5.8. RollingFileAppender
6.5.9. 日志过滤
6.5.10. 标准输出
6.5.11. MDC
6.5.12. 日志写入 MongoDB
6.5.13. 日志发送给 logstash
6.5.14. fluentd
6.5.15. Loki4j Logback
6.6. Log4j2 + Gelf + Logstash
6.6.1. Maven 配置
6.6.2. log4j2.xml 配置
6.6.3. Java 测试代码
6.6.4. Logstash 配置
6.6.5. 测试结果
6.6.6. Log4j2 更多技巧
6.7. 日志报警
6.7.1. Logstash 配置
6.7.2. 监控 SpringBootApplication 的启动和退出
6.8. Spring boot with ELK(Elasticsearch + Logstash + Kibana)
6.8.1. TCP 方案
6.8.2. Redis 方案
6.8.3. Kafka 方案
6.8.4. Other
7. Springboot with Undertow / Jetty / http2
7.1. Spring boot with Undertow
7.1.1. Maven 依赖
7.1.2. Application
7.1.3. 相关配置
7.2. Spring boot with Jetty
7.3. Spring boot with HTTP2 SSL
7.3.1. 生成自签名证书
7.3.2. application.properties 配置文件
7.3.3. 启动 Spring boot
7.3.4. restTemplate 调用实例
7.3.5. HTTP2
8. Spring boot with MongoDB
8.1. Maven
8.2. Application
8.3. MongoTemplate
8.4. Repository
9. Spring boot with MySQL
9.1. Maven
9.2. Resource
9.3. Application
9.4. JdbcTemplate
9.5. CrudRepository
10. Spring boot with Oracle
10.1. Maven
10.2. application.properties
10.3. Application
10.4. CrudRepository
10.5. JdbcTemplate
10.6. Controller
11. Spring boot with PostgreSQL
11.1. pom.xml
11.2. application.properties
11.3. Application
11.4. CrudRepository
11.5. JdbcTemplate
11.6. Controller
11.7. Test
12. Spring boot with Elasticsearch
12.1. Maven
12.2. Application
12.3. application.properties
12.4. Domain
12.5. ElasticsearchRepository
13. Spring boot with Elasticsearch TransportClient
13.1. Maven
13.2. Application
13.3. application.properties
13.4. ElasticsearchConfiguration
13.5. RestController
14. Spring boot with Apache Hive
14.1. Maven
14.2. application.properties
14.3. Configuration
14.4. CURD 操作实例
15. Spring boot with Phoenix
15.1. Maven
15.2. application.properties
15.3. Configuration
16. Spring boot with Datasource
16.1. Master / Slave 主从数据库数据源配置
16.1.1. application.properties
16.1.2. 配置主从数据源
16.1.3. 选择数据源
16.2. 多数据源配置
16.3. JPA 多数据源
17. 连接池配置
17.1. org.apache.tomcat.jdbc.pool.DataSource
17.2. druid
17.2.1. 加密数据库密码
17.3. c3p0 - JDBC3 Connection and Statement Pooling
17.4. dbcp2
17.5. bonecp
17.6. HikariPool
18. Spring boot with Queue
18.1. Spring boot with RabbitMQ(AMQP)
18.1.1. maven
18.1.2. RabbitMQConfig
18.1.3. 生产者
18.1.4. 消费者
18.2. Spring boot with Apache Kafka
18.2.1. 安装 kafka
18.2.2. maven
18.2.3. Spring boot Application
18.2.4. EnableKafka
18.2.5. KafkaListener
18.2.6. 测试
18.2.7. 完整的发布订阅实例
18.2.8. Spring cloud with Kafka
19. Spring boot with Scheduling
19.1. 启用计划任务
19.1.1. Application.java
19.1.2. 配置
19.1.3. Component
19.2. 计划任务控制开关
19.3. @Scheduled 详解
19.3.1. fixedRate 案例
19.3.2. timeUnit
19.4. cron 表达式
19.4.1. 每3秒钟一运行一次
19.4.2. 凌晨23点运行
19.4.3. 周一 ~ 周五
19.5. Timer 例子
19.6. ScheduledExecutorService 例子
20. Spring boot with Swagger
20.1. Spring boot with Springdoc
20.1.1. WebMvc
20.1.2. Webflux
20.1.3. Swagger UI
20.1.4. 从 SpringFox 迁移到 Swagger3 注解变化
20.2. Spring boot with knife4j
20.2.1. maven
20.2.2. Knife4jConfiguration
20.2.3. application.properties
20.3. springfox
20.3.1. Swagger3
20.3.2. Swagger2
20.3.3. @Api() 资源定义
20.3.4. @ApiIgnore 忽律接口
20.3.5. @ApiOperation()
20.3.6. @ApiResponses
20.3.7. @ApiModel 实体类
21. Spring boot with lombok
21.1. @Builder
21.2. @Slf4j 注解
22. Spring boot with Container
22.1. Spring boot with Docker
22.1.1. 通过 Docker 命令构建镜像
22.1.2. 通过 Maven 构建 Docker 镜像
22.1.3. [ERROR] No plugin found for prefix 'dockerfile' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (/Users/neo/.m2/repository), central (https://repo.maven.apache.org/maven2)] -> [Help 1]
22.1.4. curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:8888
22.2. Spring boot with Docker stack
22.2.1. 编译 Docker 镜像
22.2.2.
22.3. Spring boot with Kubernetes
22.3.1. Kubernetes 编排脚本
22.3.2. 部署镜像
23. Spring boot with command line
23.1. Maven
23.2. CommandLineRunner 例子
23.3. ApplicationRunner 例子
24. Spring Boot Actuator
24.1. Maven 依赖
24.2. 与 Spring Boot Actuator 有关的配置
24.2.1. 禁用HTTP端点
24.2.2. 安全配置
24.2.3. 修改 actuator 地址
24.2.4. 关机
24.3. actuator 接口
24.4. 健康状态
24.4.1. 健康状态
24.4.2. 自定义健康检查
24.5. info 配置信息
24.5.1. application.properties 配置静态信息
24.5.2. 动态信息
24.6. beans 信息
24.7. caches
24.8. conditions
24.9. configprops 配置文件
24.10. env 环境变量
24.11. logfile 日志
24.12. threaddump 线程信息
24.13. 计划任务
24.14. metrics
24.15. 控制器映射 URL
24.16. 自定义监控指标
25. SpringBootTest
25.1. Maven 依赖
25.2. 测试类
25.2.1. Junit基本注解介绍
25.3.
25.3.1. Assert.assertEquals 判断相等
25.3.2. Assert.assertTrue
25.4. JPA 测试
25.5. TestRestTemplate
25.6. Controller单元测试
25.7. WebTestClient
26. Spring boot with Aop
26.1. Aspect
26.1.1. Maven
26.1.2. Pojo 类
26.1.3. Service 类
26.1.4. Aspect 类
26.1.5. 控制器
26.1.6. Application
26.1.7. 测试
27. Spring boot with starter
27.1. 实现 starter
27.1.1. Maven pom.xml 依赖包
27.1.2. 配置文件处理
27.1.3. 自动配置文件
27.1.4. 启用 starter 的自定义注解
27.2. 引用 starter
27.2.1. Maven pom.xml 引入依赖
27.2.2. 通过注解配置 starter
27.2.3. 测试运行结果
28. Spring boot with Monitor
28.1. Spring boot with Grafana
28.1.1. Springboot 集成 InfluxDB
28.1.2. InfluxDB
28.2. Spring Boot with Prometheus
28.2.1. Maven 依赖
28.2.2. application.properties 配置文件
28.2.3. 启动类
28.2.4. 测试
28.2.5. 控制器监控
28.2.6. 自定义埋点监控
30. Spring boot with Git version
30.1. CommonRestController 公共控制器
30.2. VersionRestController 测试控制器
30.3. 创建 .gitattributes 文件
31. Spring boot with Session share
31.1. Redis
31.1.1. Maven
31.1.2. application.properties
31.1.3. Application
31.2. 测试 Session
31.3. JDBC
31.4. Springboot 2.1
32. Spring boot with Caching
32.1. maven
32.1.1. Redis
32.2. 启用缓存 @EnableCaching
32.3. 设置缓存 @Cacheable
32.3.1. 多参数处理
32.3.2. 对象参数
32.3.3.
32.3.4. 参数索引
32.3.5. 自动生成 key
32.3.6. SpEL表达式
32.3.7. 排除 null 结果
32.3.8. 排除 empty
32.4. 更新缓存 @CachePut
32.5. 删除缓存 @CacheEvict
32.6. 组合操作 @Caching
32.7. 解决Expire 和 TTL 过期时间
32.8. Cannot serialize
33. Spring boot with Email
33.1. Maven
33.2. Resource
33.3. POJO
33.4. RestController
33.5. Test
34. Spring boot with Hessian
34.1. Maven
34.2. Application
34.3. HessianServiceExporter
34.4. Service
34.5. RestController
35. Spring boot with Async
35.1. Callable 实现异步
35.2. WebAsyncTask 实现异步
35.3. DeferredResult 实现异步返回结果
35.4. 带有返回值的异步任务
35.4.1. Future
35.4.2. CompletableFuture
35.5. 默认简单线程池 SimpleAsyncTaskExecutor
35.5.1. 配置线程池
35.5.2. @Service/@Component 中异步执行
35.5.3. applicationTaskExecutor
35.6. ThreadPoolTaskExecutor 自定义线程池
35.6.1. 最简单的配置
35.6.2. 队列
35.6.3. 定义多个线程池
35.6.4. 实现 AsyncConfigurer 接口方式创建自定义连接池
35.6.5. 继承 AsyncConfigurerSupport 创建自定义连接池
35.6.6. 生产环境完整代码 @Bean 注入方式
35.6.7. 通过 @Bean 覆盖掉 SimpleAsyncTaskExecutor
35.7. 自定义线程池 ThreadPoolExecutor
35.7.1. ThreadPoolExecutor
35.7.2. 注入自定义线程池bean
35.8. 设置线程名称
35.9. 线程池监控
35.10. 注意事项
36. Springboot with Ethereum (web3j)
36.1. Maven
36.2. application.properties
36.3. TestRestController
36.4. 测试
37. Java Record 新特性
37.1. Record 替代 POJO 类
37.2. Record 作为 Properties
37.3. Record 作为实体类
37.4. Record 作为 Service
37.5. Record 作为 Controller
38. Spring boot with Retryable
38.1. @EnableResilientMethods
38.1.1. @ConcurrencyLimit 限流
38.1.2. @Retryable 重试
38.2. spring-retry
38.2.1. spring-retry 依赖
38.2.2. @EnableRetry 启用重试
38.2.3.
38.2.4. 高级用法
39. Spring Boot 4 + OpenTelemetry
39.1. 依赖配置
39.2. 定义 Span
39.3. 日志追踪

1. Spring boot with Redis

1.1. Spring boot with Redis

1.1.1. maven

				
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>			
				
			

1.1.2. application.properties

				
spring.redis.database=10
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=0
				
			

1.1.3. JUnit

				
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Test
	public void test() throws Exception {
		// 保存字符串
		stringRedisTemplate.opsForValue().set("neo", "chen");
		Assert.assertEquals("chen", stringRedisTemplate.opsForValue().get("neo"));
    }
}				
				
			

1.1.4. Controller

stringRedisTemplate模板用于存储key,value为字符串的数据

				
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@RequestMapping("/test")
	@ResponseBody
	public String test() {
		String message = "";
		stringRedisTemplate.opsForValue().set("hello", "world");
		message = stringRedisTemplate.opsForValue().get("hello");
		return message;
	}
				
			

等同于

				
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
				
			

例 2. RedisTemplate

					
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	public List<Protocol> getProtocol() {
		List<Protocol> protocols = new ArrayList<Protocol>();
		Gson gson = new Gson();
		Type type = new TypeToken<List<Protocol>>(){}.getType();
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setValueSerializer(new StringRedisSerializer());
		
		String cacheKey = String.format("%s:%s", this.getClass().getName(), Thread.currentThread().getStackTrace()[1].getMethodName());
		long expireTime = 5;
		
		if(redisTemplate.hasKey(cacheKey)){
			String cacheValue = redisTemplate.opsForValue().get(cacheKey);
			System.out.println(cacheValue);
			protocols = gson.fromJson(cacheValue, type);
		}else{
			Protocol protocol = new Protocol();
			protocol.setRequest(new Date().toString());
			protocols.add(protocol);
			
			String jsonString = gson.toJson(protocols, type);
	        System.out.println( jsonString );
			
			redisTemplate.opsForValue().set(cacheKey, jsonString);
			redisTemplate.expire(cacheKey, expireTime, TimeUnit.SECONDS);
		}
		return protocols;
	}
					
				

1.2. Redis Pub/Sub

1.2.1. Redis配置类

				
package cn.netkiller.wallet.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import cn.netkiller.wallet.redis.RedisMessageSubscriber;

@Configuration
public class RedisConfig {

	public RedisConfig() {
	}

	@Bean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
		StringRedisTemplate redisTemplate = new StringRedisTemplate();
		redisTemplate.setConnectionFactory(connectionFactory);
		return redisTemplate;
	}

	@Bean
	public MessageListenerAdapter messageListener() {
		return new MessageListenerAdapter(new RedisMessageSubscriber());
	}

	@Bean
	public ChannelTopic topic() {
		return new ChannelTopic("demo");
	}

	@Bean
	public RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory, MessageListenerAdapter messageListener) {
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();

		container.setConnectionFactory(connectionFactory);
		container.addMessageListener(messageListener(), topic());
		container.addMessageListener(messageListener(), new ChannelTopic("test"));
		return container;
	}

}

				
			

1.2.2. 订阅类

				
package cn.netkiller.wallet.redis;

import java.nio.charset.StandardCharsets;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

public class RedisMessageSubscriber implements MessageListener {
	public void onMessage(final Message message, final byte[] pattern) {
		System.out.println("Topic : " + new String(message.getChannel(), StandardCharsets.UTF_8));
		System.out.println("Message : " + message.toString());
	}
}

				
			

1.2.3. 发布类

				
package cn.netkiller.wallet.redis;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;

public class RedisMessagePublisher {

	private final StringRedisTemplate redisTemplate;

	private final ChannelTopic topic;

	public RedisMessagePublisher(StringRedisTemplate redisTemplate, ChannelTopic topic) {
		this.redisTemplate = redisTemplate;
		this.topic = topic;
	}

	public void publish(String message) {
		redisTemplate.convertAndSend(topic.getTopic(), message);
	}
}
								
				
			

1.2.4. 消息发布演示

				
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@GetMapping("/pub/demo")
	public String pub() {

		RedisMessagePublisher publisher = new RedisMessagePublisher(stringRedisTemplate, new ChannelTopic("demo"));
		String message = "Message " + UUID.randomUUID();
		publisher.publish(message);
		return message;
	}

	@GetMapping("/pub/test")
	public String pub(@RequestParam String message) {

		RedisMessagePublisher publisher = new RedisMessagePublisher(stringRedisTemplate, new ChannelTopic("test"));
		publisher.publish(message);
		return message;
	}				
				
			

1.3. Sprint boot with Redisson

1.3.1. Springboot 3.x

		

		
			

1.3.2. Springboot 2.1

注意:排除 redisson-spring-data-23,引用 redisson-spring-data-21

		
 		<dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.14.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.redisson</groupId>
                    <artifactId>redisson-spring-data-23</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-data-21</artifactId>
            <version>3.14.0</version>
        </dependency>