springboot的緩存技術(shù)的實(shí)現(xiàn)
引子
我門知道一個程序的瓶頸在于數(shù)據(jù)庫,我門也知道內(nèi)存的速度是大大快于硬盤的速度的。當(dāng)我門需要重復(fù)的獲取相同的數(shù)據(jù)的時候,我門一次又一次的請求數(shù)據(jù)庫或者遠(yuǎn)程服務(wù),導(dǎo)致大量的時間耗費(fèi)在數(shù)據(jù)庫查詢或者遠(yuǎn)程方法的調(diào)用上,導(dǎo)致程序性能的惡化,這更是數(shù)據(jù)緩存要解決的問題。
spring 緩存支持
spring定義了 org.springframework.cache.CacheManager和org.springframework.cache.Cache接口來統(tǒng)一不同的緩存技術(shù)。其中,CacheManager是Spring提供的各種緩存技術(shù)抽象接口,Cache接口包含了緩存的各種操作(增加、刪除獲得緩存,我門一般不會直接和此接口打交道)
spring 支持的CacheManager
針對不同的緩存技術(shù),需要實(shí)現(xiàn)不同的CacheManager ,spring 定義了如下表的CacheManager實(shí)現(xiàn)。

實(shí)現(xiàn)任意一種CacheManager 的時候,需要注冊實(shí)現(xiàn)CacheManager的bean,當(dāng)然每種緩存技術(shù)都有很多額外的配置,但配置CacheManager 是必不可少的。
聲明式緩存注解
spring提供了4個注解來聲明緩存規(guī)則(又是使用注解式的AOP的一個生動例子),如表。

開啟聲明式緩存
開啟聲明式緩存支持非常簡單,只需要在配置類上使用@EnabelCaching 注解即可。
springBoot 的支持
在spring中國年使用緩存技術(shù)的關(guān)鍵是配置CacheManager 而springbok 為我門自動配置了多個CacheManager的實(shí)現(xiàn)。在spring boot 環(huán)境下,使用緩存技術(shù)只需要在項目中導(dǎo)入相關(guān)緩存技術(shù)的依賴包,并配置類使用@EnabelCaching開啟緩存支持即可。
小例子
小例子是使用 springboot+jpa +cache 實(shí)現(xiàn)的。
實(shí)例步驟目錄
- 創(chuàng)建maven項目
- 數(shù)據(jù)庫配置
- jpa配置和cache配置
- 編寫bean 和dao層
- 編寫service層
- 編寫controller
- 啟動cache
- 測試校驗
1.創(chuàng)建maven項目
新建maven 項目pom.xml文件如下內(nèi)容如下:
<?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>
2.數(shù)據(jù)庫配置
在src/main/esouces目錄下新建application.properties 文件,內(nèi)容為數(shù)據(jù)庫連接信息,如下:
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
新建DBConfig.java 配置文件,配置數(shù)據(jù)源
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;
}
}
數(shù)據(jù)庫設(shè)計,數(shù)據(jù)庫只有一張Person表,設(shè)計如下:

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;
}
}
4.編寫bean 和dao層
實(shí)體類 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;
}
}
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> {
}
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);
}
實(shí)現(xiàn):(重點(diǎn),此處加緩存)
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緩存新增的或更新的數(shù)據(jù)到緩存,其中緩存名字是 people 。數(shù)據(jù)的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()+"數(shù)據(jù)做了緩存");
return p;
}
@Override
//@CacheEvict 從緩存people中刪除key為id 的數(shù)據(jù)
@CacheEvict(value = "people")
public void remove(Long id) {
System.out.println("刪除了id、key為"+id+"的數(shù)據(jù)緩存");
//這里不做實(shí)際刪除操作
}
@Override
//@Cacheable緩存key為person 的id 數(shù)據(jù)到緩存people 中,如果沒有指定key則方法參數(shù)作為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()+"數(shù)據(jù)做了緩存");
return p;
}
}
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";
}
}
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);
}
}
8.測試校驗檢驗able:
啟動Application 類,啟動后在瀏覽器輸入:http://localhost:8080/able?id=1(首先要在數(shù)據(jù)庫中初始化幾條數(shù)據(jù)。)

控制臺輸出:
“為id、key為:1數(shù)據(jù)做了緩存“ 此時已經(jīng)為此次查詢做了緩存,再次查詢該條數(shù)據(jù)將不會出現(xiàn)此條語句,也就是不查詢數(shù)據(jù)庫了。
檢驗put
在瀏覽器輸入:http://localhost:8080/put?name=abel&age=23&address=shanghai(向數(shù)據(jù)庫插入一條數(shù)據(jù),并將數(shù)據(jù)放入緩存。)

此時控制臺輸出為該條記錄做了緩存:

然后再次調(diào)用able 方法,查詢該條數(shù)據(jù),將不再查詢數(shù)據(jù)庫,直接從緩存中讀取數(shù)據(jù)。
測試evit
在瀏覽器輸入:http://localhost:8080/evit?id=1(將該條記錄從緩存中清楚,清除后,在次訪問該條記錄,將會重新將該記錄放入緩存。)
控制臺輸出:

切換緩存
1.切換為EhCache作為緩存
pom.xml 文件中添加依賴
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency>
在resource 文件夾下新建ehcache的配置文件ehcache.xml 內(nèi)容如下,此文件spring boot 會自動掃描
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!--切換為ehcache 緩存時使用--> <cache name="people" maxElementsInMemory="1000" /> </ehcache>
2.切換為Guava作為緩存
只需要在pom中添加依賴
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency>
3.切換為redis作為緩存
請看下篇博客
本文參考:《JavaEE開發(fā)的顛覆者:Spring Boot實(shí)戰(zhàn) 》
本文源代碼:https://github.com/527515025/springBoot.git
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java基于雙向環(huán)形鏈表解決丟手帕問題的方法示例
這篇文章主要介紹了java基于雙向環(huán)形鏈表解決丟手帕問題的方法,簡單描述了丟手帕問題,并結(jié)合實(shí)例形式給出了Java基于雙向環(huán)形鏈表解決丟手帕問題的步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
JavaWeb項目FullCalendar日歷插件使用的示例代碼
本篇文章主要介紹了JavaWeb項目FullCalendar日歷插件使用的示例代碼,具有一定的參考價值,有興趣的可以了解一下2017-08-08
解決bufferedReader.readLine()讀到最后發(fā)生阻塞的問題
這篇文章主要介紹了解決bufferedReader.readLine()讀到最后發(fā)生阻塞的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
SpringBoot實(shí)現(xiàn)固定和動態(tài)定時任務(wù)的三種方法
定時器是我們項目中經(jīng)常會用到的,本文主要介紹了SpringBoot實(shí)現(xiàn)固定和動態(tài)定時任務(wù)的三種方法,具有一定的參考價值,感興趣的可以了解一下2023-09-09
java foreach循環(huán)為什么不能賦值的講解
這篇文章主要介紹了java foreach循環(huán)為什么不能賦值的講解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
spring-boot使用Admin監(jiān)控應(yīng)用的方法
本篇文章主要介紹了spring-boot使用Admin監(jiān)控應(yīng)用的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
關(guān)于struts返回對象json格式數(shù)據(jù)的方法
以下為大家介紹,關(guān)于struts返回對象json格式數(shù)據(jù)的方法,希望對有需要的朋友有所幫助。2013-04-04
JAVA Iterator接口與增強(qiáng)for循環(huán)的實(shí)現(xiàn)
這篇文章主要介紹了JAVA Iterator接口與增強(qiáng)for循環(huán)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

