springboot的快取技術(轉)
springboot的快取技術
引子
我門知道一個程式的瓶頸在於資料庫,我門也知道記憶體的速度是大大快於硬碟的速度的。當我門需要重複的獲取相同的資料的時候,我門一次又一次的請求資料庫或者遠端服務,導致大量的時間耗費在資料庫查詢或者遠端方法的呼叫上,導致程式效能的惡化,這更是資料快取要解決的問題。
spring 快取支援
spring定義了 org.springframework.cache.CacheManager和org.springframework.cache.Cache介面來統一不同的快取技術。其中,CacheManager是Spring提供的各種快取技術抽象介面,Cache介面包含了快取的各種操作(增加、刪除獲得快取,我門一般不會直接和此介面打交道)
spring 支援的CacheManager
針對不同的快取技術,需要實現不同的CacheManager ,spring 定義瞭如下表的CacheManager實現。
實現任意一種CacheManager 的時候,需要註冊實現CacheManager的bean,當然每種快取技術都有很多額外的配置,但配置CacheManager 是必不可少的。
宣告式快取註解
spring提供了4個註解來宣告快取規則(又是使用註解式的AOP的一個生動例子),如表。
開啟宣告式快取
開啟宣告式快取支援非常簡單,只需要在配置類上使用@EnabelCaching 註解即可。
springBoot 的支援
在spring中國年使用快取技術的關鍵是配置CacheManager 而springbok 為我門自動配置了多個CacheManager的實現。在spring boot 環境下,使用快取技術只需要在專案中匯入相關快取技術的依賴包,並配置類使用@EnabelCaching開啟快取支援即可。
小例子
小例子是使用 springboot+jpa +cache 實現的。
例項步驟目錄
- 1.建立maven專案
- 2.資料庫配置
- 3.jpa配置和cache配置
- 4.編寫bean 和dao層
- 5.編寫service層
- 6.編寫controller
- 7.啟動cache
- 8.測試校驗
1.建立maven專案
新建maven 專案pom.xml檔案如下內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.us</groupId>
<artifactId>springboot-Cache</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<properties>
<start-class>com.us.Application</start-class>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<!--db-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
2.資料庫配置
在src/main/esouces目錄下新建application.properties 檔案,內容為資料庫連線資訊,如下:
application.properties
ms.db.driverClassName=com.mysql.jdbc.Driver
ms.db.url=jdbc:mysql://localhost:3306/cache?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
ms.db.username=root
ms.db.password=xxxxxx
ms.db.maxActive=500
- 1
- 2
- 3
- 4
- 5
新建DBConfig.java 配置檔案,配置資料來源
package com.us.example.config;
/**
* Created by yangyibo on 17/1/13.
*/
import java.beans.PropertyVetoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import com.mchange.v2.c3p0.ComboPooledDataSource;
@Configuration
public class DBConfig {
@Autowired
private Environment env;
@Bean(name="dataSource")
public ComboPooledDataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("ms.db.driverClassName"));
dataSource.setJdbcUrl(env.getProperty("ms.db.url"));
dataSource.setUser(env.getProperty("ms.db.username"));
dataSource.setPassword(env.getProperty("ms.db.password"));
dataSource.setMaxPoolSize(20);
dataSource.setMinPoolSize(5);
dataSource.setInitialPoolSize(10);
dataSource.setMaxIdleTime(300);
dataSource.setAcquireIncrement(5);
dataSource.setIdleConnectionTestPeriod(60);
return dataSource;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
資料庫設計,資料庫只有一張Person表,設計如下:
3.jpa配置
spring-data- jpa 配置檔案如下:
package com.us.example.config;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Created by yangyibo on 17/1/13.
*/
@Configuration
@EnableJpaRepositories("com.us.example.dao")
@EnableTransactionManagement
@ComponentScan
public class JpaConfig {
@Autowired
private DataSource dataSource;
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.us.example.bean");
factory.setDataSource(dataSource);
Map<String, Object> jpaProperties = new HashMap<>();
jpaProperties.put("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy");
jpaProperties.put("hibernate.jdbc.batch_size",50);
factory.setJpaPropertyMap(jpaProperties);
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
4.編寫bean 和dao層
實體類 Person.java
package com.us.example.bean;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Created by yangyibo on 17/1/13.
*/
@Entity
@Table(name = "Person")
public class Person {
@Id
@GeneratedValue
private Long id;
private String name;
private Integer age;
private String address;
public Person() {
super();
}
public Person(Long id, String name, Integer age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
dao層,PersonRepository.java
package com.us.example.dao;
import com.us.example.bean.Person;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by yangyibo on 17/1/13.
*/
public interface PersonRepository extends JpaRepository<Person, Long> {
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
5.編寫service層
service 介面
package com.us.example.service;
import com.us.example.bean.Person;
/**
* Created by yangyibo on 17/1/13.
*/
public interface DemoService {
public Person save(Person person);
public void remove(Long id);
public Person findOne(Person person);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
實現:(重點,此處加快取)
package com.us.example.service.Impl;
import com.us.example.bean.Person;
import com.us.example.dao.PersonRepository;
import com.us.example.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* Created by yangyibo on 17/1/13.
*/
@Service
public class DemoServiceImpl implements DemoService {
@Autowired
private PersonRepository personRepository;
@Override
//@CachePut快取新增的或更新的資料到快取,其中快取名字是 people 。資料的key是person的id
@CachePut(value = "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 從快取people中刪除key為id 的資料
@CacheEvict(value = "people")
public void remove(Long id) {
System.out.println("刪除了id、key為"+id+"的資料快取");
//這裡不做實際刪除操作
}
@Override
//@Cacheable快取key為person 的id 資料到快取people 中,如果沒有指定key則方法引數作為key儲存到快取中。
@Cacheable(value = "people", key = "#person.id")
public Person findOne(Person person) {
Person p = personRepository.findOne(person.getId());
System.out.println("為id、key為:"+p.getId()+"資料做了快取");
return p;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
6.編寫controller
為了測試方便請求方式都用了get
package com.us.example.controller;
import com.us.example.bean.Person;
import com.us.example.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by yangyibo on 17/1/13.
*/
@RestController
public class CacheController {
@Autowired
private DemoService demoService;
//http://localhost:8080/put?name=abel&age=23&address=shanghai
@RequestMapping("/put")
public Person put(Person person){
return demoService.save(person);
}
//http://localhost:8080/able?id=1
@RequestMapping("/able")
@ResponseBody
public Person cacheable(Person person){
return demoService.findOne(person);
}
//http://localhost:8080/evit?id=1
@RequestMapping("/evit")
public String evit(Long id){
demoService.remove(id);
return "ok";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
7.啟動cache
啟動類中要記得開啟快取配置。
package com.us.example;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import static org.springframework.boot.SpringApplication.*;
/**
* Created by yangyibo on 17/1/13.
*/
@ComponentScan(basePackages ="com.us.example")
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext run = run(Application.class, args);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
8.測試校驗
檢驗able:
啟動Application 類,啟動後在瀏覽器輸入:http://localhost:8080/able?id=1(首先要在資料庫中初始化幾條資料。)
控制檯輸出:
“為id、key為:1資料做了快取“ 此時已經為此次查詢做了快取,再次查詢該條資料將不會出現此條語句,也就是不查詢資料庫了。
檢驗put
在瀏覽器輸入:http://localhost:8080/put?name=abel&age=23&address=shanghai(向資料庫插入一條資料,並將資料放入快取。)
此時控制檯輸出為該條記錄做了快取:
然後再次呼叫able 方法,查詢該條資料,將不再查詢資料庫,直接從快取中讀取資料。
測試evit
在瀏覽器輸入:http://localhost:8080/evit?id=1(將該條記錄從快取中清楚,清除後,在次訪問該條記錄,將會重新將該記錄放入快取。)
控制檯輸出:
切換快取
1.切換為EhCache作為快取
pom.xml 檔案中新增依賴
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
- 1
- 2
- 3
- 4
在resource 資料夾下新建ehcache的配置檔案ehcache.xml 內容如下,此檔案spring boot 會自動掃描
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!--切換為ehcache 快取時使用-->
<cache name="people" maxElementsInMemory="1000" />
</ehcache>
- 1
- 2
- 3
- 4
- 5
2.切換為Guava作為快取
只需要在pom中新增依賴
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
3.切換為redis作為快取
請看下篇部落格
本文參考:《JavaEE開發的顛覆者:Spring Boot實戰 》