引子
我門知道一個程序的瓶頸在於數據庫,我門也知道內存的速度是大大快於硬盤的速度的。當我門需要重複的獲取相同的數據的時候,我門一次又一次的請求數據庫或者遠程服務,導致大量的時間耗費在數據庫查詢或者遠程方法的調用上,導致程序性能的惡化,這更是數據緩存要解決的問題。
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項目
新建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>
2.數據庫配置
在src/main/esouces目錄下新建application.properties 文件,內容為數據庫連接信息,如下:
application.properties
ms.db.driverClassName=com.mysql.jdbc.Driverms.db.url=jdbc:mysql://localhost:3306/cache?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=truems.db.username=rootms.db.password=xxxxxxms.db.maxActive=500
新建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;@Configurationpublic 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; }}數據庫設計,數據庫只有一張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@ComponentScanpublic 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層
實體類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);}實現:(重點,此處加緩存)
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. */@Servicepublic 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; }}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. */@RestControllerpublic 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@EnableCachingpublic class Application { public static void main(String[] args) { ConfigurableApplicationContext run = run(Application.class, args); }}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>
在resource 文件夾下新建ehcache的配置文件ehcache.xml 內容如下,此文件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開發的顛覆者:Spring Boot實戰》
本文源代碼:https://github.com/527515025/springBoot.git
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。