javascript
spring boot缓存_Spring Boot和缓存抽象
spring boot緩存
緩存是大多數應用程序的主要組成部分,只要我們設法避免磁盤訪問,緩存就會保持強勁。 Spring對各種配置的緩存提供了強大的支持 。 您可以根據需要簡單地開始,然后進行更多可定制的操作。
這將是spring提供的最簡單的緩存形式的示例。
Spring默認帶有一個內存緩存,它很容易設置。
讓我們從gradle文件開始。
group 'com.gkatzioura' version '1.0-SNAPSHOT'buildscript {repositories {mavenCentral()}dependencies {classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.2.RELEASE")} }apply plugin: 'java' apply plugin: 'idea' apply plugin: 'org.springframework.boot'repositories {mavenCentral() }sourceCompatibility = 1.8 targetCompatibility = 1.8dependencies {compile("org.springframework.boot:spring-boot-starter-web")compile("org.springframework.boot:spring-boot-starter-cache")compile("org.springframework.boot:spring-boot-starter")testCompile("junit:junit") }bootRun {systemProperty "spring.profiles.active", "simple-cache" }由于同一項目將用于不同的緩存提供程序,因此會有多個spring配置文件。 本教程的Spring配置文件將是簡單緩存,因為我們將使用基于ConcurrentMap的緩存,該緩存恰好是默認緩存。
我們將實現一個應用程序,該應用程序將從本地文件系統中獲取用戶信息。 該信息應位于users.json文件中
[{"userName":"user1","firstName":"User1","lastName":"First"},{"userName":"user2","firstName":"User2","lastName":"Second"},{"userName":"user3","firstName":"User3","lastName":"Third"},{"userName":"user4","firstName":"User4","lastName":"Fourth"} ]我們還將為要檢索的數據指定一個簡單的模型。
package com.gkatzioura.caching.model;/*** Created by gkatzioura on 1/5/17.*/ public class UserPayload {private String userName;private String firstName;private String lastName;public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;} }然后,我們將添加一個將讀取信息的bean。
package com.gkatzioura.caching.config;import com.fasterxml.jackson.databind.ObjectMapper; import com.gkatzioura.caching.model.UserPayload; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.io.Resource;import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collections; import java.util.List;/*** Created by gkatzioura on 1/5/17.*/ @Configuration @Profile("simple-cache") public class SimpleDataConfig {@Autowiredprivate ObjectMapper objectMapper;@Value("classpath:/users.json")private Resource usersJsonResource;@Beanpublic List<UserPayload> payloadUsers() throws IOException {try(InputStream inputStream = usersJsonResource.getInputStream()) {UserPayload[] payloadUsers = objectMapper.readValue(inputStream,UserPayload[].class);return Collections.unmodifiableList(Arrays.asList(payloadUsers));}} }顯然,為了訪問信息,我們將使用實例化的Bean包含所有用戶信息。
下一步將是創建一個存儲庫接口,以指定將要使用的方法。
package com.gkatzioura.caching.repository;import com.gkatzioura.caching.model.UserPayload;import java.util.List;/*** Created by gkatzioura on 1/6/17.*/ public interface UserRepository {List<UserPayload> fetchAllUsers();UserPayload firstUser();UserPayload userByFirstNameAndLastName(String firstName,String lastName);}現在,讓我們深入研究將包含所需緩存注釋的實現。
package com.gkatzioura.caching.repository;import com.gkatzioura.caching.model.UserPayload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Repository;import java.util.List; import java.util.Optional;/*** Created by gkatzioura on 12/30/16.*/ @Repository @Profile("simple-cache") public class UserRepositoryLocal implements UserRepository {@Autowiredprivate List<UserPayload> payloadUsers;private static final Logger LOGGER = LoggerFactory.getLogger(UserRepositoryLocal.class);@Override@Cacheable("alluserscache")public List<UserPayload> fetchAllUsers() {LOGGER.info("Fetching all users");return payloadUsers;}@Override@Cacheable(cacheNames = "usercache",key = "#root.methodName")public UserPayload firstUser() {LOGGER.info("fetching firstUser");return payloadUsers.get(0);}@Override@Cacheable(cacheNames = "usercache",key = "{#firstName,#lastName}")public UserPayload userByFirstNameAndLastName(String firstName,String lastName) {LOGGER.info("fetching user by firstname and lastname");Optional<UserPayload> user = payloadUsers.stream().filter(p-> p.getFirstName().equals(firstName)&&p.getLastName().equals(lastName)).findFirst();if(user.isPresent()) {return user.get();} else {return null;}}}包含@Cacheable的方法將觸發緩存填充,而包含@CacheEvict的方法將觸發緩存逐出。 通過使用@Cacheable而不是僅指定將存儲我們的值的緩存映射,我們還可以基于方法名稱或方法參數來指定鍵。
因此,我們實現了方法緩存。 例如,方法firstUser使用方法名稱作為鍵,而方法userByFirstNameAndLastName使用方法參數以創建鍵。
帶有@CacheEvict批注的兩種方法將清空指定的緩存。
LocalCacheEvict將是處理驅逐的組件。
package com.gkatzioura.caching.repository;import org.springframework.cache.annotation.CacheEvict; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component;/*** Created by gkatzioura on 1/7/17.*/ @Component @Profile("simple-cache") public class LocalCacheEvict {@CacheEvict(cacheNames = "alluserscache",allEntries = true)public void evictAllUsersCache() {}@CacheEvict(cacheNames = "usercache",allEntries = true)public void evictUserCache() {}}由于我們使用非常簡單的緩存形式,因此不支持驅逐ttl。 因此,我們將僅針對此特定情況添加一個調度程序,該調度程序將在一定時間段后退出緩存。
package com.gkatzioura.caching.scheduler;import com.gkatzioura.caching.repository.LocalCacheEvict; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component;/*** Created by gkatzioura on 1/7/17.*/ @Component @Profile("simple-cache") public class EvictScheduler {@Autowiredprivate LocalCacheEvict localCacheEvict;private static final Logger LOGGER = LoggerFactory.getLogger(EvictScheduler.class);@Scheduled(fixedDelay=10000)public void clearCaches() {LOGGER.info("Invalidating caches");localCacheEvict.evictUserCache();localCacheEvict.evictAllUsersCache();}}最后,我們將使用控制器來調用指定的方法
package com.gkatzioura.caching.controller;import com.gkatzioura.caching.model.UserPayload; import com.gkatzioura.caching.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** Created by gkatzioura on 12/30/16.*/ @RestController public class UsersController {@Autowiredprivate UserRepository userRepository;@RequestMapping(path = "/users/all",method = RequestMethod.GET)public List<UserPayload> fetchUsers() {return userRepository.fetchAllUsers();}@RequestMapping(path = "/users/first",method = RequestMethod.GET)public UserPayload fetchFirst() {return userRepository.firstUser();}@RequestMapping(path = "/users/",method = RequestMethod.GET)public UserPayload findByFirstNameLastName(String firstName,String lastName ) {return userRepository.userByFirstNameAndLastName(firstName,lastName);}}最后但并非最不重要的一點是,我們的Application類應包含兩個額外的注釋。 為了啟用調度程序,需要@EnableScheduling;為了啟用緩存,需要@EnableCaching
package com.gkatzioura.caching;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.scheduling.annotation.EnableScheduling;/*** Created by gkatzioura on 12/30/16.*/ @SpringBootApplication @EnableScheduling @EnableCaching public class Application {public static void main(String[] args) {SpringApplication.run(Application.class,args);}}您可以在github上找到源代碼。
翻譯自: https://www.javacodegeeks.com/2017/01/spring-boot-cache-abstraction.html
spring boot緩存
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的spring boot缓存_Spring Boot和缓存抽象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果找回删除的照片
- 下一篇: 本地运行flowable_在Cockro