您好,登錄后才能下訂單哦!
如何實現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 實現的。
實例步驟目錄
創建maven項目
數據庫配置
jpa配置和cache配置
編寫bean 和dao層
編寫service層
編寫controller
啟動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.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 配置文件,配置數據源
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; } }
數據庫設計,數據庫只有一張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; } }
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. */ @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; } }
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(首先要在數據庫中初始化幾條數據。)
控制臺輸出:
“為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>
看完上述內容,你們掌握如何實現springboot緩存技術的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。