Spring Boot实战学习笔记4

来源:互联网 发布:linux copy 覆盖 编辑:程序博客网 时间:2024/06/06 00:09

title: Spring Boot实战学习笔记4
tags:Spring Boot实战
grammar_cjkRuby: true


摘要

本文为学习Java EE开发的颠覆者 Spring Boot实战的学习笔记,学习了一遍,但是好记性不如烂笔头,所以文章记录下来。图书购买地址为: https://item.jd.com/11894632.html.

Spring Boot实战学习笔记1

Spring Boot实战学习笔记2

Spring Boot实战学习笔记3

Spring Boot实战学习笔记4

Spring Boot实战学习笔记5

SpringBoot常用属性配置

1.Spring 基础

2.Spring 常用配置

3.Spring 高级话题

4.Spring mvc基础

6.Spring Boot核心

7.Spring Boot的Web开发

7.1 Sring Boot的Web开发支持

Web支持包括支持自动配置内嵌Servlet容器,自动配置http的编码,自动配置上传文件的属性,自动配置mappingJackson2Http,自动配置Spring MVC .

7.2 Thymeleaf模板引擎

SpringBoot支持模板引擎:FreeMarker,Groovy,Thymeleaf,Velocity,Mustache.推荐使用Thymeleaf.
Thymeleaf是java类库,一个xml/xhtml/html5的模板引擎.

7.3 Web相关配置

7.3.1 Spring Boot提供的自动配置

  • 自动配置的ViewResolver
    包括ContentNegotiatingViewResolver,BeanNameViewResolver,InternalResourceViewResolver
  • 自动配置的静态资源
    addResourceHandlers,定义了以下静态资源的自动配置.
    • 类路径文件
      类路径下/static,/public,/resource和/META-INF/resource文件夹下的静态文件直接映射为/,通过http://localhost:ip/来访问.
    • webjar
      webjar是将我们常用的脚本框架封装在jar包中的jar包.查看 www.webjars.org.
      webjar放置在/META-INF/resources/webjars下的静态文件映射成/webjar/,通过http://localhost:ip/webjar/来访问
  • 自动配置的Formatter和Converter
    定义Converter,GenericConverter和Formatter接口实现类的Bean.就会自动注册到Spring MVC中.
  • 自动配置的HttpMessageConverters
    可以自定义HttpMessageConverter,只需自定义HttpMessageConverters的Bean,然后在此Bean中注册自定义HttpMessageConverter即可.
  • 静态首页的支持
    index文件放置在如下目录:
    • classpath:/MEAT-INF/resources/index.html
    • classpath:/resource/index.html
    • classpath:/static/index.html
    • classpath:/public/index.html

7.3.2 接管Spring Boot的Web配置

不用Spring MVC的配置类,自己实现配置.
不用@EnableWebMVC注解.

///ch7_2/src/main/java/com/wisely/WebMvcConfig.java @Configurationpublic class WebMvcConfig  extends WebMvcConfigurerAdapter{     @Override       public void addViewControllers(ViewControllerRegistry registry) {           registry.addViewController("/xx").setViewName("/xx");       }}

7.3.3 注册Servlet,filter,Listener

  • 直接注册Bean
    • 通过将Servlet,Filter,Listener声明为Spring Bean而到达注册的效果.
  • 通过RegistrationBean
    • 注册ServletRegistrationBean,FilterRegistrationBean和ServletListenerRegistrationBean.

7.4 Tomcat配置

7.4.1 配置Tomcat

  • 配置Servlet容器

    # EMBEDDED SERVER CONFIGURATION (ServerProperties)
    server.port=8080
    server.address= # bind to a specific NIC
    server.session-timeout= # session timeout in seconds
    server.context-parameters.*= # Servlet context init parameters, e.g. server.context-parameters.a=alpha
    server.context-path= # the context path, defaults to '/'
    server.servlet-path= # the servlet path, defaults to '/'
  • 配置Tomcat

    server.tomcat.uri-encoding=UTF-8 # Character encoding to use to decode the URI.

    ### 7.4.2 代码配置Tomcat
    • 通用配置
    • 新建类

      /ch7_4/src/main/java/com/wisely/ch7_4/CustomServletContainer.java
    • 当前配置文件内配置

      /ch7_4/src/main/java/com/wisely/ch7_4/Ch74Application.java-->CustomServletContainer
      -->servletContainer
    • 特定配置

      /ch7_4/src/main/java/com/wisely/ch7_4/Ch74Application.java-->servletContainer

7.4.3 替换Tomcat

  • 替换Jetty
    在pom.xml中将spring-boot-starter-web的依赖从spring.boot-starter-tomcat修改为spring-boot-start-Jetty
  • 替换为Undertow
    在pom.xml中将spring-boot-starter-web的依赖从spring.boot-starter-tomcat修改为spring-boot-start-undertow

7.4.4 SSL配置

SSL(Secure Sockets Layer,安全套接层)是为网络通信提供安全及数据完整性的一种安全协议,SSL在网络传输层对网络连接进行加密.SSL协议位于TCP/IP,协议与各种应用层协议之间,为数据通信提供安全支持.
SSL分为两层
- SSL记录协议(SSL Record)
建立在可靠的传输协议(如TCP)之上,为高层协议提供数据封装,压缩,加密等基本功能的支持.
- SSL握手协议(SSL Handshake Protocol)
建立在SSL记录协议之上,用于在实际数据传输开始前,通信双方进行身份认证,写上加密算法,交换加密密钥等.
- HTTPS
在B/S中,通过HTTPS来实现SSL.https是以安全为目标的HTTP通道,在http下加入SSL,https的安全基础是SSL.

7.4.1 生成证书

windows版本JDK目录下的bin中有keytools.exe,cmd后进入输入

keytool -genkey -alias tomcatencrypt -keyalg RSA  //如果不指定算法格式的话,会使用老的加密格式,高版本的容器,都会报安全格式不支持的错误

按照提示输入密码,姓名,住址,地区,国家等信息.生成了一个.keystore文件(在C:\Users\username目录下).

7.4.2 Spring Boot配置SSL

添加一个index.html到/src/main/resources/static目录下测试备用

server.port=8443  //1指定监听端口 #server.session.timeout=#server.context-path=server.tomcat.uri-encoding=UTF-8#server.tomcat.compression= #新版已经没有了server.ssl.key-store=.keystore  //2ssl存储的文件名 server.ssl.key-store-password=111111 //3证书密码 server.ssl.key-store-type=JKS   //4证书类型 server.ssl.key-alias=tomcatencrypt  //5证书别名

此时启动springboot时会有日志显示(https),浏览器访问时需要用https.

7.4.3 http转向https

让浏览器自动转向https.需要配置: TomcatEmbeddedServletContainerFactory.并添加tomcat的connector来实现.

/ch7_4/src/main/java/com/wisely/ch7_4/Ch74Application.java/ch7_4/src/main/java/com/wisely/ch7_4/CustomServletContainer.java

本7.4节内容还可以参考博客
Spring Boot中的容器配置和SSL支持

7.5 Favicon配置

favicon默认开启,关闭用配置:

spring.mvc.favicon.enabled=false

设置自己的favicon,放同名文件favicon.ico放在类路径根目录,类路径/META-INF/resources/,类路径/static/或类路径public下

7.6 WebSocket

WebSocket为浏览器和服务端提供了双工异步通信的功能,即浏览器可以向服务器发送消息,服务器也可以想浏览器发送消息. 需要IE10+,Chrome13+,Firefox6+.
是通过一个socket来实现双工异步通信能力.
Spring boot提供的自动配置: WebSocketAutoConfiguration
starer.pom为spring-boot-starter-websocket

@Configuration@ConditionalOnClass({ Servlet.class, ServerContainer.class })@ConditionalOnWebApplication@AutoConfigureBefore(EmbeddedServletContainerAutoConfiguration.class)public class WebSocketAutoConfiguration {}
  • 广播式
/ch7_6/src/main/java/com/wisely/ch7_6/WebSocketConfig.java/ch7_6/src/main/java/com/wisely/ch7_6/domain/WiselyMessage.java/ch7_6/src/main/java/com/wisely/ch7_6/domain/WiselyResponse.java/ch7_6/src/main/java/com/wisely/ch7_6/web/WsController.java/ch7_6/src/main/resources/templates/ws.html/ch7_6/src/main/java/com/wisely/ch7_6/WebMvcConfig.java
  • 点对点式
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-security</artifactId></dependency>/ch7_6/src/main/java/com/wisely/ch7_6/WebSecurityConfig.java    /ch7_6/src/main/java/com/wisely/ch7_6/WebSocketConfig.java/ch7_6/src/main/java/com/wisely/ch7_6/web/WsController.java/ch7_6/src/main/resources/templates/login.html/ch7_6/src/main/resources/templates/chat.html/ch7_6/src/main/java/com/wisely/ch7_6/WebMvcConfig.java

7.7 基于Bootstrap和AngularJS的现代Web应用

支持Bootstrap

7.7.1 AngularJS

AngularJS:用来设计web应用..
AngularJS:使用声明式模板+数据绑定(类似JSP,Thymeleaf).MVW(model+view+whatever),MVVM(model-view-viewmodel),MVC(model-view-controller).Javascript重要.
有例子和源码查看 /ch7_7.
本节细节请查看图书.

8.Spring Boot的数据访问

Spring Data 项目是spring 解决数据访问的解决方案. Spring data是一个伞形项目.
Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问计数,包括非关系数据库、Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。
spring-data官网链接

Main modules

  • Spring Data Commons - Core Spring concepts underpinning every Spring Data project.
  • Spring Data Gemfire - Provides easy configuration and access to GemFire from Spring applications.
  • Spring Data JPA - Makes it easy to implement JPA-based repositories.
  • Spring Data KeyValue - Map-based repositories and SPIs to easily build a Spring Data module for key-value - stores.
  • Spring Data LDAP - Provides Spring Data repository support for Spring LDAP.
  • Spring Data MongoDB - Spring based, object-document support and repositories for MongoDB.
  • Spring Data REST - Exports Spring Data repositories as hypermedia-driven RESTful resources.
  • Spring Data Redis - Provides easy configuration and access to Redis from Spring applications.
  • Spring Data for Apache Cassandra - Spring Data module for Apache Cassandra.
  • Spring Data for Apache Solr - Spring Data module for Apache Solr.

Community modules

  • Spring Data Aerospike - Spring Data module for Aerospike.
  • Spring Data Couchbase - Spring Data module for Couchbase.
  • Spring Data DynamoDB - Spring Data module for DynamoDB.
  • Spring Data Elasticsearch - Spring Data module for Elasticsearch.
  • Spring Data Hazelcast - Provides Spring Data repository support for Hazelcast.
  • Spring Data Neo4j - Spring based, object-graph support and repositories for Neo4j.

Related modules

  • Spring Data JDBC Extensions - Provides extensions to the JDBC support provided in the Spring Framework.
  • Spring for Apache Hadoop - Simplifies Apache Hadoop by providing a unified configuration model and easy to use APIs for using HDFS, MapReduce, Pig, and Hive.

Spring Data Commons Spring Data为我们使用统一的API来对上述的数据存储技术数据访问提供支持. 通过Spring Data Commons来实现. Spring Data commons是上述Spring Data的依赖. 它形成统一标准,包含了CRUD(创建(Create)、更新(Update)、读取(Retrieve)和删除(Delete)),查询,排序,分页等操作. Spring Data Repository 是Spring Data commons的重要概念,可以极大减少数据访问层的代码,定义和了各种数据访问的接口.

public interface Repository<T, ID extends Serializable> {}@NoRepositoryBeanpublic interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {    /**     * Saves a given entity. Use the returned instance for further operations as the save operation might have changed the     * entity instance completely.     *      * @param entity     * @return the saved entity     */    <S extends T> S save(S entity);    /**     * Saves all given entities.     *      * @param entities     * @return the saved entities     * @throws IllegalArgumentException in case the given entity is (@literal null}.     */    <S extends T> Iterable<S> save(Iterable<S> entities);    /**     * Retrieves an entity by its id.     *      * @param id must not be {@literal null}.     * @return the entity with the given id or {@literal null} if none found     * @throws IllegalArgumentException if {@code id} is {@literal null}     */    T findOne(ID id);    /**     * Returns whether an entity with the given id exists.     *      * @param id must not be {@literal null}.     * @return true if an entity with the given id exists, {@literal false} otherwise     * @throws IllegalArgumentException if {@code id} is {@literal null}     */    boolean exists(ID id);    /**     * Returns all instances of the type.     *      * @return all entities     */    Iterable<T> findAll();    /**     * Returns all instances of the type with the given IDs.     *      * @param ids     * @return     */    Iterable<T> findAll(Iterable<ID> ids);    /**     * Returns the number of entities available.     *      * @return the number of entities     */    long count();    /**     * Deletes the entity with the given id.     *      * @param id must not be {@literal null}.     * @throws IllegalArgumentException in case the given {@code id} is {@literal null}     */    void delete(ID id);    /**     * Deletes a given entity.     *      * @param entity     * @throws IllegalArgumentException in case the given entity is (@literal null}.     */    void delete(T entity);    /**     * Deletes the given entities.     *      * @param entities     * @throws IllegalArgumentException in case the given {@link Iterable} is (@literal null}.     */    void delete(Iterable<? extends T> entities);    /**     * Deletes all entities managed by the repository.     */    void deleteAll();}

Repository的层次结构如下:
image

8.1 引入Docker

8.2 Spring Data JPA

8.2.1 JPA实例

JPA: java persistence API.是基于O/R映射(Object-Relational Mapping)的标准规范. 也可以自定义Repository.

8.2.2 Spring boot的支持

spring-boot-starter-data-jpa,依赖于spring-boot-starter-jdbc

源码可查看:/ch8_2

参考文章:
Spring ORM+Hibernate?Out!换 Spring Data JPA 吧!
深入浅出学Spring Data JPA

8.3 Spring Data REST

8.3.1 点睛Spring Data REST

可以讲repository自动输出为REST资源.Spring Data REST支持将Spring Data JPA,Spring Data MongoDB,Spring Data Neo4j,Spring Data GemFire以及Spring Data Cassandra的repository自动转换成REST服务.
Spring Data REST的配置定义在RepositoryRestMvcConfiguration中.可以通过继承或导入方式来实现.

8.3.2 Spring boot的支持

spring-boot-starter-data-rest 配置以spring.data.rest开头.

8.3.3 实战

postman测试

源码可查看:/ch8_3

8.4 声明式事务

8.4.1 Spring的事务机制

PlatformTransactionManager接口.不同数据访问的事物实现不同的接口.

数据访问技术 实现 JDBC DataSourceTransactionManager JPA JpaTransactionManager Hibernate HibernateTransactionManager JDO JdoTransactionManager 分布式事务 JtaTransactionManager

实现接口如下:

PlatformTransactionManager接口实现类

本地事务系列之二:使用PlatformTransactionManager

8.4.2 声明式事务

@Transactional 注解在方法上表明该方法需要事务支持. 是基于AOP的实现操作. 被注解的方法被调用时,spring开启一个新的事物,当方法无异常结束后,spring会提交这个事务.
不是javax.transaction.Transactional,而是org.springframework.transaction.annotation.Transactional.
注意要开启配置:@EnableTransactionManagement

8.4.3 注解事务行为

从传播属性(Propagation),隔离级别(Isolation Level)和常用参数.另外还有 数据库事务正确执行的四个要素

传播属性(Propagation)

属性类型 说明 MANDATORY[强制的] 方法必须有事务,没有事务则抛异常 NEVER 方法不能事务中,如果有事务则抛异常 REQUIRED [默认] Method A,A No Trans->New Trans T1,if A->Method B,B用T1, if B 发生Excep,则回滚B 和 A REQUIRES_NEW Method A 和MethodB,无论谁,则NEW Trans T,互不影响. NESTED[嵌套的] Method A 和MethodB,无论谁,则NEW Trans T,互不影响.支持JDBC,不支持JPA和hibernate NOT_SUPPORTED 方法不在事务中执行,如果有事务,方法调用结束阶段,事务都挂起 SUPPORTS 方法有事务则用事务,没有就不用事务

隔离级别(Isolation Level)

级别 中文 说明 产生影响 DEFAULT 默认 oracle,sql server是READ_COMMITTED,mysql是REPEATABLE_READ READ_UNCOMMITTED 读未提交 A事务中有修改,没提交;B事务能读到A的修改 产生脏读,不可重复读,幻读 READ_COMMITTED 读已提交 A事务中修改,且提交,B事务才可以读到提交后记录 阻止脏读,导致不可重复读和幻读 REPEATABLE_READ 可重复读 能实现READ_COMMITTED的功能,还能阻止A读取一条记录时,B事务不允许修改这条数据 阻止脏读和不可重复读,但可出现幻读 SERIALIZABLE 串行化 此级别事务是顺序执行的 避免全部,但是开销大 隔离级别/异常情况 Dirty reads non-repeatable reads phantom reads Serializable 不会 不会 不会 REPEATABLE 不会 不会 会 READ COMMITTED 不会 会 会 Read Uncommitted 会 会 会

常用参数

名称 类型 说明 详解 timeout s,默认TIMEOUT_DEFAULT 超时时间,以秒为单位 该属性用于设置事务的超时秒数,默认值为-1表示永不超时 readOnly boolean,默认false 事务读写性 该属性用于设置当前事务是否为只读事务,设置为true表示只读,false则表示可读写,默认值为false。
例如:@Transactional(readOnly=true) rollbackFor Class[] 一组异常类,遇到时回滚 该属性用于设置需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,则进行事务回滚。例如:指定单一异常类:@Transactional(rollbackFor=RuntimeException.class),指定多个异常类:@Transactional(rollbackFor={RuntimeException.class, Exception.class}) rollbackForClassName Stirng[] 一组异常类名,遇到时回滚 该属性用于设置需要进行回滚的异常类名称数组,当方法中抛出指定异常名称数组中的异常时,则进行事务回滚。例如:指定单一异常类名称:@Transactional(rollbackForClassName=”RuntimeException”);指定多个异常类名称:@Transactional(rollbackForClassName={“RuntimeException”,”Exception”}) noRollbackFor Class[] 一组异常类,遇到时不回滚。默认为{} 该属性用于设置不需要进行回滚的异常类数组,当方法中抛出指定异常数组中的异常时,不进行事务回滚。例如:指定单一异常类:@Transactional(noRollbackFor=RuntimeException.class);指定多个异常类:@Transactional(noRollbackFor={RuntimeException.class, Exception.class}) noRollbackForClassName 枚举orgStirng[]值 一组异常类名,遇到时不回滚,默认为{} 该属性用于设置不需要进行回滚的异常类名称数组,当方法中抛出指定异常名称数组中的异常时,不进行事务回滚。例如:指定单一异常类名称:@Transactional(noRollbackForClassName=”RuntimeException”);指定多个异常类名称:@Transactional(noRollbackForClassName={“RuntimeException”,”Exception”}) propagation 枚举org.springframework.transaction.annotation.Propagation的值 事务传播行为 例如:@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) isolation 枚举org.springframework.transaction.annotation.Isolation的值 事务隔离级别 该属性用于设置底层数据库的事务隔离级别,事务隔离级别用于处理多事务并发的情况,通常使用数据库的默认隔离级别即可,基本不需要进行设置 value String 可选的限定描述符,指定使用的事务管理器

四大要素ACID

英文名称 中文名称 备注 Atomicity 原子性 事务是数据库的逻辑工作单位,它对数据库的修改要么全部执行,要么全部不执行 Consistemcy 一致性 事务前后,数据库的状态都满足所有的完整性约束 Isolation 隔离性 并发执行的事务是隔离的,一个不影响一个。如果有两个事务,运行在相同的时间内,执行相同的功能,事务的隔离性将确保每一事务在系统中认为只有该事务在使用系统。这种属性有时称为串行化,为了防止事务操作间的混淆,必须串行化或序列化请求,使得在同一时间仅有一个请求用于同一数据。通过设置数据库的隔离级别,可以达到不同的隔离效果。 Durability 持久性 在事务完成以后,该事务所对数据库所作的更改便持久的保存在数据库之中,并不会被回滚

常见问题

类型名称 备注 更新丢失 两个事务都同时更新一行数据,但是第二个事务却中途失败退出,导致对数据的两个修改都失效了。这是因为系统没有执行任何的锁操作,因此并发事务并没有被隔离开来。 脏读(Dirty Reads) 脏读又称无效数据读出。一个事务读取另外一个事务还没有提交的数据叫脏读。 不可重复读(Non-Repeatable Reads) 不可重复读是指在同一个事务内,两个相同的查询返回了不同的结果。 幻读(Phantom Reads) 事务在操作过程中进行两次查询,第二次查询的结果包含了第一次查询中未出现的数据或者缺少了第一次查询中出现的数据

非重复度和幻像读的区别:
非重复读是指同一查询在同一事务中多次进行,由于其他提交事务所做的修改或删除,每次返回不同的结果集,此时发生非重复读。(A transaction rereads data it has previously read and finds that another committed transaction has modified or deleted the data. )

幻像读是指同一查询在同一事务中多次进行,由于其他提交事务所做的插入操作,每次返回不同的结果集,此时发生幻像读。(A transaction reexecutes a query returning a set of rows that satisfies a search condition and finds that another committed transaction has inserted additional rows that satisfy the condition. )
表面上看,区别就在于非重复读能看见其他事务提交的修改和删除,而幻像能看见其他事务提交的插入。

脏读例如:事务T1修改了一行数据,但是还没有提交,这时候事务T2读取了被事务T1修改后的数据,之后事务T1因为某种原因Rollback了,那么事务T2读取的数据就是脏的

例如:事务T1读取某一数据,事务T2读取并修改了该数据,T1为了对读取值进行检验而再次读取该数据,便得到了不同的结果。

例如:系统管理员A将数据库中所有学生的成绩从具体分数改为ABCDE等级,但是系统管理员B就在这个时候插入了一条具体分数的记录,当系统管理员A改结束后发现还有一条记录没有改过来,就好像发生了幻觉一样。这就叫幻读。

以上的4种问题(更新丢失、脏读、不可重复读、幻读)都和事务的隔离级别有关。通过设置事务的隔离级别,可以避免上述问题的发生。

spring事务传播属性和隔离级别
Spring事物隔离级别以及事物的七种传播特性详细介绍,以及应用当中需要注意的点
数据库事务中的隔离级别和锁+spring Transactional注解

8.4.4 类级别使用@Transactional

@Transactional用在类上后,相当于该类所有的public方法都用来@Transactional注解,开启了事务.

8.4.5 Spring Data JPA

SimpleJpaRepository
默认开启事务.readOnly=true;但是save,delete方法重写了@Transactional,readOnly的属性是false.

8.4.6 Spring Boot的事务支持

  • 自动配置的事务管理器
    使用DataSourceTransactionManager实现了PlatformTransactinManager,
    自动配置在org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
    源码如下:
@Configuration@ConditionalOnClass({ JdbcTemplate.class, PlatformTransactionManager.class })@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)public class DataSourceTransactionManagerAutoConfiguration {    @Autowired(required = false)    private DataSource dataSource;    @Bean    @ConditionalOnMissingBean(PlatformTransactionManager.class)    @ConditionalOnBean(DataSource.class)    public DataSourceTransactionManager transactionManager() {        return new DataSourceTransactionManager(this.dataSource);    }    @ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class)    @Configuration    @EnableTransactionManagement    protected static class TransactionManagementConfiguration {    }}
  • 自动开启注解事务的支持
    配置事务类: org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration
    源码如下:
@Configuration@ConditionalOnClass({ TransactionTemplate.class, PlatformTransactionManager.class })@ConditionalOnSingleCandidate(PlatformTransactionManager.class)@AutoConfigureAfter({ JtaAutoConfiguration.class, JpaBaseConfiguration.class,        DataSourceTransactionManagerAutoConfiguration.class })public class TransactionAutoConfiguration {    @Autowired    private PlatformTransactionManager transactionManager;    @Bean    @ConditionalOnMissingBean    public TransactionTemplate transactionTemplate() {        return new TransactionTemplate(this.transactionManager);    }}

8.4.7 实战

源码查看: /ch8_4

8.5 数据缓存Cache

8.5.1 Spring 缓存支持

org.springframework.cache.CacheManager :提供抽象接口

public interface CacheManager {    /**     * Return the cache associated with the given name.     * @param name the cache identifier (must not be {@code null})     * @return the associated cache, or {@code null} if none found     */    Cache getCache(String name);    /**     * Return a collection of the cache names known by this manager.     * @return the names of all caches known by the cache manager     */    Collection<String> getCacheNames();}

CacheManager的实现类:

image

org.springframework.cache.Cache:提供缓存操作(增加,删除,获得缓存)

public interface Cache {    String getName();    Object getNativeCache();    ValueWrapper get(Object key);    <T> T get(Object key, Class<T> type);    void put(Object key, Object value);    ValueWrapper putIfAbsent(Object key, Object value);    void evict(Object key);    void clear();    interface ValueWrapper {        /**         * Return the actual value in the cache.         */        Object get();    }}

Cache实现类:

image

  • Spring支持的CacheManager
CacheMananger 描述 SimpleCacheManager 使用简单的Collection来存储缓存,主要用来测试用途 ConcurrentMapCacheManager 使用ConcurrentMap来存储缓存 NoOpCacheManager 仅测试用途,不会实际存储缓存 EhCacheCacheManager 使用EhCache作为缓存技术 GuavaCacheManager 使用Google Guava的GuavaCache作为缓存技术 HazelcastCacheManager 使用Hazelcat作为缓存技术 JCacheCacheManager 支持JCache(JSR-107)标准的实现作为缓存技术,如Apache CommonsJCS RedisCacheManager 使用Redis作为缓存技术
  • 声明式缓存注解
注解 解释 @Cacheable 在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据,如果没有疏忽局,则调用方法并将方法返回值放进缓存 @CachePut 无论怎样,都会将方法的返回值放到缓存中.@CachePut的属性与@Cacheable保持一致. @CacheEvict 将一条或多条数据从缓存中删除 @Cacheing 可以通过@Cacheing注解组合多个注解策略在一个方法上.

- 开启声明式缓存支持

@Configuration@EnableCachingpublic class Appconfig(){}

8.5.2 Spring boot的支持

通过@EnableCaching来开启缓存配置
缓存相关类在org.springframework.boot.autoconfigure.cache包下 ,自动配置类为CacheAutoConfiguration
image

配置文件以spring.cache开头 ,配置文件类为CacheProperties
image

spring.cache.type=  #可选generic,ehcache,hazelcast,infinispan,jcache,redis,guava,simple,nonespring.cache.cacheNames=  #程序启动时创建缓存名称spring.cache.ehcache.config=  #ehcache的配置文件spring.cache.hazelcast.config=  #hazelcast的配置文件spring.cache.infinispan.config=  #infinispan的配置文件spring.cache.jcache.config=  #jcache的配置文件spring.cache.jcache.provider=  #当多个jcache实现在类路径中的时候,指定jcache的实现spring.cache.guava.spec=  #如配置名称

8.5.3 实战

依赖Cache(spring-boot-starter-cache)
源码查看/ch8_5

@Servicepublic class DemoServiceImpl implements DemoService {    @Autowired    PersonRepository personRepository;    @Override    @CachePut(value = "people", key = "#person.id")//1新增或更新数据到缓存,缓存名称为people,key是person的id    public Person save(Person person) {        Person p = personRepository.save(person);        System.out.println("为id、key为:"+p.getId()+"数据做了缓存");        return p;    }    @Override    @CacheEvict(value = "people")//2从缓存people中删除key为id的缓存    public void remove(Long id) {        System.out.println("删除了id、key为"+id+"的数据缓存");        //这里不做实际删除操作    }    @Override    @Cacheable(value = "people", key = "#person.id")//3缓存key为person的id数据到people中    public Person findOne(Person person) {        Person p = personRepository.findOne(person.getId());        System.out.println("为id、key为:"+p.getId()+"数据做了缓存");        return p;    }}//注意,如果没有指定key,则方法参数作为key保存到缓存中

8.5.4 切换缓存技术

使用的缓存不一样需要引进的jar也不一样.

    //Ehcache依赖    <dependency>        <groupId>net.sf.ehcache</groupId>        <artifactId>ehcache</artifactId>    </dependency>    //自动扫描类路径下的ehcache.xml    <?xml version="1.0" encoding="UTF-8"?>    <ehcache>    <cache name="people" maxElementsInMemory="1000" />    </ehcache>    //guava依赖    <dependency>        <groupId>com.google.guava</groupId>        <artifactId>guava</artifactId>        <version>18.0</version>    </dependency>    //redis依赖    <>dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-redis</artifactId>    </dependency>

Spring Cache抽象详解
SpringBoot学习笔记(6) SpringBoot数据缓存Cache [Guava和Redis实现]
@Cacheable注解在spring3中的使用-实现缓存

8.6 NoSQL

8.6.1 MongoDB

依赖:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>
  • Spring 支持1 MongoTemplate方式

  • Spring 支持2 Repository方式

  • Spring Boot的支持

自动配置:

org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\

@EnableConfigurationProperties 开启Mongo相关配置
MongoProperties mongo相关配置类

/ch8_6_1

8.6.2 Redis

依赖:

    <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-redis</artifactId></dependency>
  • Spring的支持
    链接ConnectionFactory,有JedisConnectionFactory(Jedis),JredisConnectionFactory(Jredis),LettuceConnectionFactory(Lettuce),SrpConnectionFactory(Spullara/redis-protocol)

  • Spring Boot的支持
    自动配置:

org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\

RedisProperties Redis相关配置

注意:需要支持多实例模式.
/ch8_6_2
//////后续需要将实际开发中使用到的redis单例和集群的配置方式整理出.

9.Spring Boot的企业级开发

10.Spring Boot开发部署与测试

11.Spring 应用监控

Spring Boot有四大神器,分别是auto-configuration、starters、cli、actuator

12.分布式系统开发

原创粉丝点击