springboot的緩存技術(shù)的實(shí)現(xiàn)
引子
我門(mén)知道一個(gè)程序的瓶頸在于數(shù)據(jù)庫(kù),我門(mén)也知道內(nèi)存的速度是大大快于硬盤(pán)的速度的。當(dāng)我門(mén)需要重復(fù)的獲取相同的數(shù)據(jù)的時(shí)候,我門(mén)一次又一次的請(qǐng)求數(shù)據(jù)庫(kù)或者遠(yuǎn)程服務(wù),導(dǎo)致大量的時(shí)間耗費(fèi)在數(shù)據(jù)庫(kù)查詢(xún)或者遠(yuǎn)程方法的調(diào)用上,導(dǎo)致程序性能的惡化,這更是數(shù)據(jù)緩存要解決的問(wèn)題。
spring 緩存支持
spring定義了 org.springframework.cache.CacheManager和org.springframework.cache.Cache接口來(lái)統(tǒng)一不同的緩存技術(shù)。其中,CacheManager是Spring提供的各種緩存技術(shù)抽象接口,Cache接口包含了緩存的各種操作(增加、刪除獲得緩存,我門(mén)一般不會(huì)直接和此接口打交道)
spring 支持的CacheManager
針對(duì)不同的緩存技術(shù),需要實(shí)現(xiàn)不同的CacheManager ,spring 定義了如下表的CacheManager實(shí)現(xiàn)。
實(shí)現(xiàn)任意一種CacheManager 的時(shí)候,需要注冊(cè)實(shí)現(xiàn)CacheManager的bean,當(dāng)然每種緩存技術(shù)都有很多額外的配置,但配置CacheManager 是必不可少的。
聲明式緩存注解
spring提供了4個(gè)注解來(lái)聲明緩存規(guī)則(又是使用注解式的AOP的一個(gè)生動(dòng)例子),如表。
開(kāi)啟聲明式緩存
開(kāi)啟聲明式緩存支持非常簡(jiǎn)單,只需要在配置類(lèi)上使用@EnabelCaching 注解即可。
springBoot 的支持
在spring中國(guó)年使用緩存技術(shù)的關(guān)鍵是配置CacheManager 而springbok 為我門(mén)自動(dòng)配置了多個(gè)CacheManager的實(shí)現(xiàn)。在spring boot 環(huán)境下,使用緩存技術(shù)只需要在項(xiàng)目中導(dǎo)入相關(guān)緩存技術(shù)的依賴(lài)包,并配置類(lèi)使用@EnabelCaching開(kāi)啟緩存支持即可。
小例子
小例子是使用 springboot+jpa +cache 實(shí)現(xiàn)的。
實(shí)例步驟目錄
- 創(chuàng)建maven項(xiàng)目
- 數(shù)據(jù)庫(kù)配置
- jpa配置和cache配置
- 編寫(xiě)bean 和dao層
- 編寫(xiě)service層
- 編寫(xiě)controller
- 啟動(dòng)cache
- 測(cè)試校驗(yàn)
1.創(chuàng)建maven項(xiàng)目
新建maven 項(xiàng)目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ù)庫(kù)配置
在src/main/esouces目錄下新建application.properties 文件,內(nèi)容為數(shù)據(jù)庫(kù)連接信息,如下:
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ù)庫(kù)設(shè)計(jì),數(shù)據(jù)庫(kù)只有一張Person表,設(shè)計(jì)如下:
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.編寫(xiě)bean 和dao層
實(shí)體類(lèi) 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.編寫(xiě)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 中,如果沒(méi)有指定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.編寫(xiě)controller
為了測(cè)試方便請(qǐng)求方式都用了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.啟動(dòng)cache
啟動(dòng)類(lèi)中要記得開(kāi)啟緩存配置。
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.測(cè)試校驗(yàn)檢驗(yàn)able:
啟動(dòng)Application 類(lèi),啟動(dòng)后在瀏覽器輸入:http://localhost:8080/able?id=1(首先要在數(shù)據(jù)庫(kù)中初始化幾條數(shù)據(jù)。)
控制臺(tái)輸出:
“為id、key為:1數(shù)據(jù)做了緩存“ 此時(shí)已經(jīng)為此次查詢(xún)做了緩存,再次查詢(xún)?cè)摋l數(shù)據(jù)將不會(huì)出現(xiàn)此條語(yǔ)句,也就是不查詢(xún)數(shù)據(jù)庫(kù)了。
檢驗(yàn)put
在瀏覽器輸入:http://localhost:8080/put?name=abel&age=23&address=shanghai(向數(shù)據(jù)庫(kù)插入一條數(shù)據(jù),并將數(shù)據(jù)放入緩存。)
此時(shí)控制臺(tái)輸出為該條記錄做了緩存:
然后再次調(diào)用able 方法,查詢(xún)?cè)摋l數(shù)據(jù),將不再查詢(xún)數(shù)據(jù)庫(kù),直接從緩存中讀取數(shù)據(jù)。
測(cè)試evit
在瀏覽器輸入:http://localhost:8080/evit?id=1(將該條記錄從緩存中清楚,清除后,在次訪(fǎng)問(wèn)該條記錄,將會(huì)重新將該記錄放入緩存。)
控制臺(tái)輸出:
切換緩存
1.切換為EhCache作為緩存
pom.xml 文件中添加依賴(lài)
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency>
在resource 文件夾下新建ehcache的配置文件ehcache.xml 內(nèi)容如下,此文件spring boot 會(huì)自動(dòng)掃描
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!--切換為ehcache 緩存時(shí)使用--> <cache name="people" maxElementsInMemory="1000" /> </ehcache>
2.切換為Guava作為緩存
只需要在pom中添加依賴(lài)
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency>
3.切換為redis作為緩存
請(qǐng)看下篇博客
本文參考:《JavaEE開(kāi)發(fā)的顛覆者:Spring Boot實(shí)戰(zhàn) 》
本文源代碼:https://github.com/527515025/springBoot.git
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java基于雙向環(huán)形鏈表解決丟手帕問(wèn)題的方法示例
這篇文章主要介紹了java基于雙向環(huán)形鏈表解決丟手帕問(wèn)題的方法,簡(jiǎn)單描述了丟手帕問(wèn)題,并結(jié)合實(shí)例形式給出了Java基于雙向環(huán)形鏈表解決丟手帕問(wèn)題的步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-11-11JavaWeb項(xiàng)目FullCalendar日歷插件使用的示例代碼
本篇文章主要介紹了JavaWeb項(xiàng)目FullCalendar日歷插件使用的示例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08解決bufferedReader.readLine()讀到最后發(fā)生阻塞的問(wèn)題
這篇文章主要介紹了解決bufferedReader.readLine()讀到最后發(fā)生阻塞的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07SpringBoot實(shí)現(xiàn)固定和動(dòng)態(tài)定時(shí)任務(wù)的三種方法
定時(shí)器是我們項(xiàng)目中經(jīng)常會(huì)用到的,本文主要介紹了SpringBoot實(shí)現(xiàn)固定和動(dòng)態(tài)定時(shí)任務(wù)的三種方法,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09java foreach循環(huán)為什么不能賦值的講解
這篇文章主要介紹了java foreach循環(huán)為什么不能賦值的講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09spring-boot使用Admin監(jiān)控應(yīng)用的方法
本篇文章主要介紹了spring-boot使用Admin監(jiān)控應(yīng)用的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09一起來(lái)學(xué)習(xí)JAVA的運(yùn)算符
這篇文章主要為大家詳細(xì)介紹了JAVA的運(yùn)算符,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-03-03關(guān)于struts返回對(duì)象json格式數(shù)據(jù)的方法
以下為大家介紹,關(guān)于struts返回對(duì)象json格式數(shù)據(jù)的方法,希望對(duì)有需要的朋友有所幫助。2013-04-04JAVA Iterator接口與增強(qiáng)for循環(huán)的實(shí)現(xiàn)
這篇文章主要介紹了JAVA Iterator接口與增強(qiáng)for循環(huán)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11