9.1 Spring Boot之Web
1. Spring Boot集成Thymeleaf
配置前缀:spring.thymeleaf。
项目引入:thymeleaf-spring5。
在classpath路径下的templates目录下新建hello.html文件。主要学习一下循环标签语法。
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<table>
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr th:each="user,userState : ${users}">
<td th:text="${userState.index}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</tbody>
</table>
</body>
</html>
语法:th:each="obj,iterStat:${objList}"。属性有:Index、Count、Size、Current、even/odd、First、Last。
2. Spring Boot集成JSP
引入依赖:tomcat-embed-jasper、jstl、javax.servlet-api,第一个来源于org.apache.tomcat.embed,后两个来源于javax.servlet。学习新的迭代循环语法:
<c:forEach var="data" items="${users}" varStatus="loop">
<tr>
<td>${loop.index + 1}</td>
<td>${data.name}</td>
<td>${data.age}</td>
</tr>
</c:forEach>
注意设置view的映射关系。
spring.mvc.view.prefix=/view/
spring.mvc.view.suffix=.jsp
9.2 Spring Boot之Data
1. 基于注解的MyBatis集成
定义Mapper接口,使用@Results和@Result创建映射集,使用@ResultMap引用,使用@Insert、@Delete、@Update、@Select于接口方法前执行SQL语句。在Mapper接口前注解@Mapper,并在main方法类前开启@MapperScan("包名")。基于XML的配置方法已学过且繁琐,略过,注意在application.properties中设置一些属性即可
mybatis.type-aliases-package=包名
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
2. Spring Boot集成Redis
引入依赖:spring-boot-starter-data-redis、commons-pool2以及JSP所需相关依赖。
属性配置:redis可配置host、password、port、timeout、database等。其中.lettuce.pool还可配置min-idle、max-idle、max-wait、max-active等。
实例:Redis一般通过key-value存储数据,key一般都是String。value若为String可直接使用StringRedisTemplate,若为Object则需自定义RedisTemplate。
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {
@Bean
public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
在Controller类中注入StringRedisTemplate或RedisTemplate即可直接使用。使用时调用他们的opsForValue()方法返回实例的getter或setter方法(传入key参数)即可。
3. Spring Boot集成MyBatis使用Redis做缓存
@Cacheable和@CachePut主要针对方法配置,能够根据方法的请求参数对其结果进行缓存。后者每次都会触发真实方法的调用,实际是对方法返回值进行缓存的。包括value、key、condition三个参数。引用字段加#。示例:@Cacheable(value={"cache1", "cache2"}),@CachePut(value="test", condition="#userName.length()>2")。
@CacheEvict主要针对方法配置,能够根据一定的条件对缓存进行清空。参数在以上三种基础上还包含allEntries(是否清空所有缓存内容,默认false)、beforeInvocation(是否在方法执行前就清空,默认false)。
@CacheConfig用于类前声明,省略此类中所有方法前缓存注解的value参数,使用cacheNames指定。
注意最后在主类前加上@EnableCaching。此外注意Spring Boot默认扫描主类所在包,需使用@ComponentScan(basePackages={...})确保扫描到所有类。
4. Spring Boot集成RabbitMQ
引入依赖:spring-boot-starter-amqp。配置spring.application.name=spring-boot-rabbitmq。spring.rabbit.mq下还可配置host、port、username、password等。
生产者、消息队列、消费者是最重要的三个概念。RabbitMQ还额外添加了一个交换机模块,它有四种类型:
Direct
默认类型,指定一个BindingKey,发送消息时指定对应Key,当两者一致时消息将被发送到该消息队列中。发送者调用AmqpTemplate的实例方法convertAndSend(key, value)发送,在需要接受的类(消费者)前使用@RabbitListener(queue="...")注解,该类的特定方法前使用@RabbitHandler注解。配置示例代码:
@Configuration
public class RabbitConfig {
@Bean
public org.springframework.amqp.core.Queue Queue() {
return new org.springframework.amqp.core.Queue("hello");
}
}
发送对象时,POJO类需实现Serializable接口和一系列setter和getter方法,使用方式同上。
Topic
在配置类中设置对应的queue与binding,其他同上即可。需要在配置类中实现queueXXX、exchange、bindingExchangeXXX方法,注意BindingBuilder中的.bind、.to、.with以及通配符#的使用。
@Configuration
public class TopicRabbitConfig {
final static String message = "topic.message";
final static String messages = "topic.messages";
@Bean
public Queue queueMessage() {
return new Queue(TopicRabbitConfig.message);
}
@Bean
public Queue queueMessages() {
return new Queue(TopicRabbitConfig.messages);
}
@Bean
TopicExchange exchange() {
return new TopicExchange("topicExchange");
}
@Bean
Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) {
return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message");
}
@Bean
Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) {
return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#");
}
}
Headers
根据一组键值对规则进行匹配,书中未介绍。
Fanout
又叫广播模式,需要在配置类中实现XXXMessage、fanoutExchange、bindingExchangeXXX方法。注意BindingBuilder中的.bind、.to的使用。
@Configuration
public class FanoutRabbitConfig {
@Bean
public Queue AMessage() {
return new Queue("fanout.A");
}
@Bean
public Queue BMessage() {
return new Queue("fanout.B");
}
@Bean
public Queue CMessage() {
return new Queue("fanout.C");
}
@Bean
FanoutExchange fanoutExchange() {
return new FanoutExchange("fanoutExchange");
}
@Bean
Binding bindingExchangeA(Queue AMessage, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(AMessage).to(fanoutExchange);
}
@Bean
Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(BMessage).to(fanoutExchange);
}
@Bean
Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(CMessage).to(fanoutExchange);
}
}
9.3 Spring Boot之集成其他工具
1. Spring Boot集成Druid
引入依赖druid-spring-boot-starter,并设置Druid属性。属性前缀spring.datasource.druid,详见P219~220。
2. Spring Boot定时任务
开源框架有Quartz等。使用@Scheduled即可注解定时任务,主要包含四个属性:
cron:时间表达式,包含6个或7个域。从左到右依次可包含的字符如下(名称只需理解):(/表示per,每)
Seconds:,-*/或0~59的整数。
Minutes:,-*/或0~59的整数。
Hours:,-*/或0~23的整数。
DayofMonth:,-*/?LWC或0~31的整数。
Month:,-*/或1~12的整数或JAN-DEC。
DayofWeek:,-*/?LC#或1~7的整数或SUN-SAT。(1表示星期天,2表示星期一等)
Year:,-*/或1970~2099的整数。
fixedRate:上一个调用开时候再次调用的延时。
fixedDelay:方法执行完成后延迟。
initialDelay:第一次执行延迟。
最后在主类前注解@EnableScheduling来开启。
3. Spring Boot集成Swagger2
可帮助设计、构建、记录和使用REST API。Swagger通过注解表明该接口会生成文档。需引入相关依赖:springfox-swagger2、springfox-swagger-ui,groupId均为io.springfox。
常用注解如下(书上有部分错误,省略):
@Api:修饰整个类
@ApiOperation:描述一个方法,即接口。
@ApiParam:单个参数描述。
@ApiModel:用对象来接收参数。
@ApiProperty:描述对象的一个字段。
@ApiResponse:返回值说明。
@ApiResponses:返回值说明。
@ApiIgnore:忽略该API。
@ApiImplicitParam:方法参数的说明。
@ApiImplicitParams:方法参数的说明。
@ApiParam用于方法的参数前,而@ApiImplicitParam用于@ApilmplicitParams内,在接口前。详见@ApiParam @PathVariable @RequestParam三者区别 - 高山_流水 - 博客园 (cnblogs.com)
与启动类同级包建立Swagger2。示例代码如下:
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.webdemo"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot 测试使用 Swagger2 构建RESTful API")
.contact(new Contact("社会主义接班人", "", "991843897@qq.com"))
.version("1.0")
.description("用户管理")
.build();
}
}
在需要设置接口信息的API中使用注解设置一系列注解信息。除以上所列注解外可学习/**注释的使用:在IDEA中,在方法声明前一行输入/**回车,会自动生成该方法的注释,自动生成@param、@return等注解。在启动类中设置@MapperScan,默认界面路径为/swagger-ui.html。
4. Spring Boot打包部署
首先在pom.xml中设置<packaging>war</packaging>,再使用exclusion移除嵌入式Tomcat插件(spring-boot-starter-tomcat),添加servlet-api的依赖(javax.servlet-api或tomcat-servlet-api任选其一),修改启动类继承SpringBootServletInitializer并重写configure方法。
@SpringBootApplication
@MapperScan("com.example.mapper")
public class SpringBootSwaggerApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringBootSwaggerApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringBootSwaggerApplication.class, args);
}
}
在项目根目录(包含pom.xml的目录下),在命令行里输入mvn clean package即可。将target目录下的war包放到tomcat的webapps目录下,启动tomcat,即可自动解压部署。默认URL:http://localhost:[端口号]/[打包项目名]/。
关于IDEA中打包Maven项目:直接在Maven插件中找到生命周期,执行install即可,生成war包存放在/target/目录下。