Spring启动和缓存抽象

缓存是大多数应用程序的主要组成部分,只要我们设法避免磁盘访问,缓存就会保持强劲。 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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/352406.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

关于python的if条件语句,whilefor循环等的简单说。

if 条件1:# 语句体# elif 条件2:# 语句体# elif 条件3:# 语句体# else:# 语句体 #从键盘输入一个值# num 8# num1 int(input("请输入一个整数&#xff1a;"))if num1 num: print("您猜对了")elif num1 < num:print("您猜小了")else:print(…

haproxy配置代理tomcat和nginx_你真的掌握LVS、Nginx及HAProxy工作原理吗?

当前大多数的互联网系统都使用了服务器集群技术&#xff0c;集群是将相同服务部署在多台服务器上构成一个集群整体对外提供服务。图片来自 Unsplash这些集群可以是 Web 应用服务器集群&#xff0c;也可以是数据库服务器集群&#xff0c;还可以是分布式缓存服务器集群等等。在实…

PostgreSQL新手入门

自从MySQL被Oracle收购以后&#xff0c;PostgreSQL逐渐成为开源关系型数据库的首选。 本文介绍PostgreSQL的安装和基本用法&#xff0c;供初次使用者上手。以下内容基于Debian操作系统&#xff0c;其他操作系统实在没有精力兼顾&#xff0c;但是大部分内容应该普遍适用。 一、安…

使用Junit和Easytest进行数据驱动的测试

在本文中&#xff0c;我们将看到如何使用Junit进行数据驱动的测试。 为此&#xff0c;我将使用一个名为EasyTest的库。 众所周知&#xff0c;对于TestNG&#xff0c;它已内置了数据提供程序。 通过简单的测试&#xff0c;我们可以使用Junit进行数据驱动的测试。 什么是数据驱…

Matlab代码的耗时分析、优化、加速

Profile(分析&#xff09; 在加速你的matlab程序之前&#xff0c;你需要知道你的代码哪一部分运行最慢。matlab提供个简单的机制&#xff0c;让你能够知道你 的代码的某一部分运行所占用CPU时间。通过在代码段开始添加tic&#xff0c;及在结束添加toc&#xff1b;matlab就能计算…

python整数逆序输出_利用Python实现倒序任意整数

这是很早以前学习C时候做过的一个练习题&#xff0c;题目的要求大概是把用户输入的三位数倒序输出&#xff0c;比如说用户输入123&#xff0c;然后程序应该输出的结果是321。如果遇到用户输入100&#xff0c;那么程序应该输出1。然后我给扩展一下&#xff0c;这个程序来适应于三…

谜题61:日期游戏

下面的程序演练了Date和Calendar类的某些基本特性&#xff0c;它会打印出什么呢&#xff1f; import java.util.*;public class DatingGame {public static void main(String[ ] args) { Calendar cal Calendar.getInstance(); cal.set(1999, 12, 31); // Year, Month, Day Sy…

Java 中Thread的sleep、join、yield方法解析

1.Thread中sleep方法作用是使当前线程等待&#xff0c;其他线程开始执行&#xff0c;如果有线程锁&#xff0c;sleep不会让出锁 没有加锁代码如下&#xff1a; public class SynchronizedSleepMethod {public static void main(String[] args) {MoneyMethod moneyMethod new M…

MySQL与PostgreSQL:该选择哪个开源数据库?哪一个更好?

Naresh Kumar是一位软件工程师与热情的博主&#xff0c;对编程与新事物充满了激情和兴趣。近日&#xff0c;Naresh撰写了一篇博文&#xff0c;对开源世界最常见的两种数据库MySQL与PostgreSQL的特点进行了详尽的分析和比对。 如果打算为项目选择一款免费、开源的数据库&#x…

jquery select change事件_jQuery实现省市联动效果

<!DOCTYPE html> <html><head><meta charset"UTF-8"><title></title></head><body><select name"province"id"province"><option >请选择</option></select><selec…

MATLAB上的GPU加速计算——学习笔记

MATLAB目前只支持Nvidia的显卡。如果你的显卡是AMD的或者是Intel的&#xff0c;就得考虑另寻它路了。 MATLAB可谓工程计算中的神器&#xff0c;一方面它自带丰富的函数库&#xff0c;另一方面它所有的数据都是内建的矩阵类型&#xff0c;最后画图也方便&#xff0c;因此解决一…

java中代码块的概述_Java代码质量工具–概述

java中代码块的概述最近&#xff0c;我有机会在本地IT社区聚会上介绍了该主题。 这是基本演示&#xff1a; Java代码质量工具 以及更有意义的思维导图&#xff1a; 但是&#xff0c;我认为我需要更深入地探讨这一主题。 此博客文章应该像是在此方向上进行进一步调查的起点。 …

js原型、原型链、作用链、闭包全解

https://www.2cto.com/kf/201711/698876.html 【对象、变量】 一个对象就是一个类&#xff0c;可以理解为一个物体的标准化定义。它不是一个具体的实物&#xff0c;只是一个标准。而通过对象实例化得到的变量就是一个独立的实物。比如通过一个对象定义了“人”&#xff0c;通过…

Mysql 简介

一 简介&#xff1a;MySQL是最流行的开放源码SQL数据库管理系统&#xff0c;它是由MySQL AB公司开发、发布并支持的。MySQL AB是由多名MySQL开发人创办的一家商业公司。它是一家第二代开放源码公司&#xff0c;结合了开放源码价值取向、方法和成功的商业模型。 1.MySQL是一种数…

python高阶函数闭包装饰器_5.初识python装饰器 高阶函数+闭包+函数嵌套=装饰器...

一.什么是装饰器&#xff1f; 实际上装饰器就是个函数&#xff0c;这个函数可以为其他函数提供附加的功能。 装饰器在给其他函数添加功能时&#xff0c;不会修改原函数的源代码&#xff0c;不会修改原函数的调用方式。 高阶函数&#xff0b;函数嵌套&#xff0b;闭包 &#xff…

Matlab 画图字体,字号的设定,图片大小和比例

figure_FontSize12; set(get(gca,XLabel),FontSize,figure_FontSize,Vertical,top); set(get(gca,YLabel),FontSize,figure_FontSize,Vertical,middle); set(findobj(FontSize,12),FontSize,figure_FontSize); %这4句是将字体大小改为8号字&#xff0c;在小图里很清晰 %set(gcf…

使用Speedment和Spring创建REST API

随着Spring Boot的第4版发布&#xff0c;为Web开发企业应用程序变得非常容易。 代表开发人员仍然需要大量时间的事情是&#xff0c;例如在Hibernate中对现有数据库进行建模&#xff0c;以获取数据的面向对象的视图。 在本教程中&#xff0c;我们将探索如何与开源一起使用开源工…

Phpstorm界面不停的indexing,不停的闪烁

选择 File->Invalidate Caches / Restart...->Invalidate and Restart&#xff0c;就行了&#xff01;转载于:https://www.cnblogs.com/php-no-2/p/9848606.html

Matlab 集群计算平台搭建

家庭云服务器高阶应用&#xff1a;通过Matlab分布式计算来演示所谓的“家庭云计算”&#xff08;非云储存&#xff09;(转)Matlab是强大的计算软件&#xff0c;这不需要过多介绍了&#xff0c;大到航天航空领域&#xff0c;小到计算方程式&#xff0c;Matlab无处不在。 像是这种…

c打印无符号整数_C语言基础知识:printf的输出格式,C/C++语言编程讲解

C语言基础知识&#xff1a;printf的输出格式printf()函数是格式输出函数&#xff0c;请求printf()打印变量的指令取决与变量的类型&#xff0e;例如&#xff0c;在打印整数是使用&#xff05;d符号&#xff0c;在打印字符是用&#xff05;c 符号&#xff0e;这些符号被称为转换…