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.5. 命令行注入配置项
5.5.1. spring.profiles.active 参数切换配置文件
5.5.2. SpringApplicationBuilder.properties() 方法添加配置项
5.5.3. 禁用命令行注入环境变量
5.6.
5.7. PropertyResolver 获取配置
5.8. 参数引用
5.9. 默认值
5.10. 产生随机数
5.10.1. 随机数
5.11. 多行字符串
5.12. 注入多值属性 arrays, list, set
5.13. List 列表类型
5.14. Map类型
5.15. Binder
5.16. 加密 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.2.1. lombok
6.3. logback 配置详解
6.3.1. 标准输出
6.3.2. 禁止 logback 日志输出
6.3.3. 指定Class过滤日志
6.3.4. configuration 属性配置
6.3.5. contextName 设置上下文名称
6.3.6. property 设置变量
6.3.7. encoder 日志格式设置
6.3.8. RollingFileAppender
6.3.9. 日志过滤
6.3.10. 标准输出
6.3.11. MDC
6.3.12. 日志写入 MongoDB
6.3.13. 日志发送给 logstash
6.3.14. fluentd
6.3.15. Loki4j Logback
6.4. Log4j2 + Gelf + Logstash
6.4.1. Maven 配置
6.4.2. log4j2.xml 配置
6.4.3. Java 测试代码
6.4.4. Logstash 配置
6.4.5. 测试结果
6.4.6. Log4j2 更多技巧
6.5. 日志报警
6.5.1. Logstash 配置
6.5.2. 监控 SpringBootApplication 的启动和退出
6.6. Spring boot with ELK(Elasticsearch + Logstash + Kibana)
6.6.1. TCP 方案
6.6.2. Redis 方案
6.6.3. Kafka 方案
6.6.4. Other
7. Spring boot with Undertow
7.1. Maven 依赖
7.2. Application
7.3. 相关配置
8. Spring boot with Jetty
9. Spring boot with HTTP2 SSL
9.1. 生成自签名证书
9.2. application.properties 配置文件
9.3. 启动 Spring boot
9.4. restTemplate 调用实例
9.5. HTTP2
10. Spring boot with MongoDB
10.1. Maven
10.2. Application
10.3. MongoTemplate
10.4. Repository
11. Spring boot with MySQL
11.1. Maven
11.2. Resource
11.3. Application
11.4. JdbcTemplate
11.5. CrudRepository
12. Spring boot with Oracle
12.1. Maven
12.2. application.properties
12.3. Application
12.4. CrudRepository
12.5. JdbcTemplate
12.6. Controller
13. Spring boot with PostgreSQL
13.1. pom.xml
13.2. application.properties
13.3. Application
13.4. CrudRepository
13.5. JdbcTemplate
13.6. Controller
13.7. Test
14. Spring boot with Elasticsearch
14.1. Maven
14.2. Application
14.3. application.properties
14.4. Domain
14.5. ElasticsearchRepository
15. Spring boot with Elasticsearch TransportClient
15.1. Maven
15.2. Application
15.3. application.properties
15.4. ElasticsearchConfiguration
15.5. RestController
16. Spring boot with Apache Hive
16.1. Maven
16.2. application.properties
16.3. Configuration
16.4. CURD 操作实例
17. Spring boot with Phoenix
17.1. Maven
17.2. application.properties
17.3. Configuration
18. Spring boot with Datasource
18.1. Master / Slave 主从数据库数据源配置
18.1.1. application.properties
18.1.2. 配置主从数据源
18.1.3. 选择数据源
18.2. 多数据源配置
18.3. JPA 多数据源
19. 连接池配置
19.1. org.apache.tomcat.jdbc.pool.DataSource
19.2. druid
19.2.1. 加密数据库密码
19.3. c3p0 - JDBC3 Connection and Statement Pooling
19.4. dbcp2
19.5. bonecp
19.6. HikariPool
20. Spring boot with Queue
20.1. Spring boot with RabbitMQ(AMQP)
20.1.1. maven
20.1.2. RabbitMQConfig
20.1.3. 生产者
20.1.4. 消费者
20.2. Spring boot with Apache Kafka
20.2.1. 安装 kafka
20.2.2. maven
20.2.3. Spring boot Application
20.2.4. EnableKafka
20.2.5. KafkaListener
20.2.6. 测试
20.2.7. 完整的发布订阅实例
20.2.8. Spring cloud with Kafka
21. Spring boot with Scheduling
21.1. 启用计划任务
21.1.1. Application.java
21.1.2. 配置
21.1.3. Component
21.2. 计划任务控制开关
21.3. @Scheduled 详解
21.3.1. fixedRate 案例
21.3.2. timeUnit
21.4. cron 表达式
21.4.1. 每3秒钟一运行一次
21.4.2. 凌晨23点运行
21.4.3. 周一 ~ 周五
21.5. Timer 例子
21.6. ScheduledExecutorService 例子
22. Spring boot with Swagger
22.1. Spring boot with Springdoc
22.1.1. WebMvc
22.1.2. Webflux
22.1.3. Swagger UI
22.1.4. 从 SpringFox 迁移到 Swagger3 注解变化
22.2. Spring boot with knife4j
22.2.1. maven
22.2.2. Knife4jConfiguration
22.2.3. application.properties
22.3. springfox
22.3.1. Swagger3
22.3.2. Swagger2
22.3.3. @Api() 资源定义
22.3.4. @ApiIgnore 忽律接口
22.3.5. @ApiOperation()
22.3.6. @ApiResponses
22.3.7. @ApiModel 实体类
23. Spring boot with lombok
23.1. @Builder
23.2. @Slf4j 注解
24. Spring boot with Container
24.1. Spring boot with Docker
24.1.1. 通过 Docker 命令构建镜像
24.1.2. 通过 Maven 构建 Docker 镜像
24.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]
24.1.4. curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:8888
24.2. Spring boot with Docker stack
24.2.1. 编译 Docker 镜像
24.2.2.
24.3. Spring boot with Kubernetes
24.3.1. Kubernetes 编排脚本
24.3.2. 部署镜像
25. Spring boot with command line
25.1. Maven
25.2. CommandLineRunner 例子
25.3. ApplicationRunner 例子
26. Spring Boot Actuator
26.1. Maven 依赖
26.2. 与 Spring Boot Actuator 有关的配置
26.2.1. 禁用HTTP端点
26.2.2. 安全配置
26.2.3. 修改 actuator 地址
26.2.4. 关机
26.3. actuator 接口
26.4. 健康状态
26.4.1. 健康状态
26.5. info 配置信息
26.6. beans 信息
26.7. caches
26.8. conditions
26.9. configprops 配置文件
26.10. env 环境变量
26.11. logfile 日志
26.12. threaddump 线程信息
26.13. 计划任务
26.14. metrics
26.15. 控制器映射 URL
26.16. 自定义监控指标
27. SpringBootTest
27.1. Maven 依赖
27.2. 测试类
27.2.1. Junit基本注解介绍
27.3.
27.3.1. Assert.assertEquals 判断相等
27.3.2. Assert.assertTrue
27.4. JPA 测试
27.5. TestRestTemplate
27.6. Controller单元测试
27.7. WebTestClient
28. Spring boot with Aop
28.1. Aspect
28.1.1. Maven
28.1.2. Pojo 类
28.1.3. Service 类
28.1.4. Aspect 类
28.1.5. 控制器
28.1.6. Application
28.1.7. 测试
29. Spring boot with starter
29.1. 实现 starter
29.1.1. Maven pom.xml 依赖包
29.1.2. 配置文件处理
29.1.3. 自动配置文件
29.1.4. 启用 starter 的自定义注解
29.2. 引用 starter
29.2.1. Maven pom.xml 引入依赖
29.2.2. 通过注解配置 starter
29.2.3. 测试运行结果
30. Spring boot with Monitor
30.1. Spring boot with Grafana
30.1.1. Springboot 集成 InfluxDB
30.1.2. InfluxDB
30.2. Spring Boot with Prometheus
30.2.1. Maven 依赖
30.2.2. application.properties 配置文件
30.2.3. 启动类
30.2.4. 测试
30.2.5. 控制器监控
30.2.6. 自定义埋点监控
32. Spring boot with Git version
32.1. CommonRestController 公共控制器
32.2. VersionRestController 测试控制器
32.3. 创建 .gitattributes 文件
33. Spring boot with Session share
33.1. Redis
33.1.1. Maven
33.1.2. application.properties
33.1.3. Application
33.2. 测试 Session
33.3. JDBC
33.4. Springboot 2.1
34. Spring boot with Caching
34.1. maven
34.1.1. Redis
34.2. 启用 Cache
34.3. @Cacheable 的用法
34.3.1. SpEL表达式
34.3.2. 排除 null 结果
34.3.3. 排除 empty
34.4. @CachePut 用法
34.5. 清空缓存
34.6. @Caching
34.7. 解决Expire 和 TTL 过期时间
35. Spring boot with Email
35.1. Maven
35.2. Resource
35.3. POJO
35.4. RestController
35.5. Test
36. Spring boot with Hessian
36.1. Maven
36.2. Application
36.3. HessianServiceExporter
36.4. Service
36.5. RestController
37. Spring boot with Async
37.1. Callable 实现异步
37.2. WebAsyncTask 实现异步
37.3. DeferredResult 实现异步返回结果
37.4. 带有返回值的异步任务
37.4.1. Future
37.4.2. CompletableFuture
37.5. 默认简单线程池 SimpleAsyncTaskExecutor
37.5.1. 配置线程池
37.5.2. @Service/@Component 中异步执行
37.5.3. applicationTaskExecutor
37.6. ThreadPoolTaskExecutor 自定义线程池
37.6.1. 最简单的配置
37.6.2. 队列
37.6.3. 定义多个线程池
37.6.4. 实现 AsyncConfigurer 接口方式创建自定义连接池
37.6.5. 继承 AsyncConfigurerSupport 创建自定义连接池
37.6.6. 生产环境完整代码 @Bean 注入方式
37.6.7. 通过 @Bean 覆盖掉 SimpleAsyncTaskExecutor
37.7. 自定义线程池 ThreadPoolExecutor
37.7.1. ThreadPoolExecutor
37.7.2. 注入自定义线程池bean
37.8. 设置线程名称
37.9. 线程池监控
37.10. 注意事项
38. Springboot with Ethereum (web3j)
38.1. Maven
38.2. application.properties
38.3. TestRestController
38.4. 测试
39. Java Record 新特性
39.1. Record 替代 POJO 类
39.2. Record 作为 Properties
39.3. Record 作为实体类
39.4. Record 作为 Service
39.5. Record 作为 Controller

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());
	}
}

				
			
				
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.3. 消息发布演示

				
	@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>