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 实现的。

实例步骤目录

  • 1.创建maven项目
  • 2.数据库配置
  • 3.jpa配置和cache配置
  • 4.编写bean 和dao层
  • 5.编写service层
  • 6.编写controller
  • 7.启动cache
  • 8.测试校验

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 {@Autowiredprivate 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 {@Autowiredprivate DataSource dataSource;@Beanpublic 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();}@Beanpublic 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@GeneratedValueprivate 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 {@Autowiredprivate 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 {@Autowiredprivate 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")@ResponseBodypublic 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>

3.切换为redis作为缓存

请看下篇博客

本文参考:《JavaEE开发的颠覆者:Spring Boot实战 》

本文源代码:https://github.com/527515025/springBoot.git

 

见:http://blog.csdn.net/u012373815/article/details/54564076

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

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

相关文章

深度优先遍历解决连通域求解问题-python实现

问题描述 在一个矩形网格中每一个格子的颜色或者为白色或者为黑色。任意或上、或下、或左、或右相邻同为黑色的格子组成一个家族。家族中所有格子的数量反映家族的大小。要求找出最大家族的家族大小&#xff08;组成最大家族的格子的数量&#xff09;并统计出哪些点属于哪一族。…

字符串进阶

C风格字符串 1、字符串是用字符型数组存储的&#xff0c;字符串要求其尾部以’\0’作为结束标志。如&#xff1a; char string[ ]”C programming language”; 用sizeof来测string长度为25个字节&#xff0c;而实际串本身长度(含空格)为24个字节&#xff0c;多出来的一个就是…

flask上传excel文件,无须存储,直接读取内容

运行环境python3.6 import xlrd from flask import Flask, requestapp Flask(__name__)app.route("/", methods[POST, GET]) def filelist1():print(request.files)file request.files[file]print(file, type(file), file)print(file.filename) # 打印文件名f …

分布式 ID的 9 种生成方式

一、为什么要用分布式 ID&#xff1f; 在说分布式 ID 的具体实现之前&#xff0c;我们来简单分析一下为什么用分布式 ID&#xff1f;分布式 ID 应该满足哪些特征&#xff1f; 1、什么是分布式 ID&#xff1f; 拿 MySQL 数据库举个栗子&#xff1a; 在我们业务数据量不大的时…

spring boot Redis集成—RedisTemplate

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 Spring boot 基于Spring, Redis集成与Spring大同小异。 文章示例代码均以前篇笔记为基础增加修改&#xff0c;直接上代码&#xff1a;…

QtCreator无法编辑源文件

在Qt Creator中新建工程&#xff0c;添加现有C源文件&#xff0c;有的源文件可以编辑&#xff0c;有的源文件编辑不了&#xff0c;发现无法编辑的源文件有一个共同特点&#xff0c;即其中都包含中文&#xff0c;且中文出现乱码&#xff0c;于是&#xff0c;点击Qt Creator菜单栏…

Unicode简介和使用

一、Unicode简介 在第一章中&#xff0c;我已经预告&#xff0c;C语言中在Microsoft Windows程序设计中扮演着重要角色的任何部分都会讲述到&#xff0c;您也许在传统文字模式程序设计中还尚未遇到过这些问题。宽字符集和Unicode差不多就是这样的问题。 简单地说&#xff0c;…

webpack4.x 模块化浅析-CommonJS

先看下webpack官方文档中对模块的描述&#xff1a; 在模块化编程中&#xff0c;开发者将程序分解成离散功能块(discrete chunks of functionality)&#xff0c;并称之为模块。每个模块具有比完整程序更小的接触面&#xff0c;使得校验、调试、测试轻而易举。 精心编写的模块提供…

设计模式--抽象工厂(个人笔记)

一、抽象工厂的应用场景以及优缺点 1 应用场景&#xff1a; 如果系统需要多套的代码解决方案&#xff0c;并且每套的代码解决方案中又有很多相互关联的产品类型&#xff0c;并且在系统中我们可以相互替换的使用一套产品的时候可以使用该模式&#xff0c;客户端不需要依赖具体的…

利用阿里云OSS对文件进行存储,上传等操作

--pom.xml加入阿里OSS存储依赖 <!--阿里云OSS存储--> <dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>2.8.3</version> </dependency> --配置阿里云oss相关常量参数 /…

Java并发编程之ThreadGroup

ThreadGroup是Java提供的一种对线程进行分组管理的手段&#xff0c;可以对所有线程以组为单位进行操作&#xff0c;如设置优先级、守护线程等。 线程组也有父子的概念&#xff0c;如下图&#xff1a; 线程组的创建 1 public class ThreadGroupCreator {2 3 public static v…

springboot 缓存ehcache的简单使用

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 步骤&#xff1a; 1. pom文件中加 maven jar包&#xff1a; <!-- ehcache 缓存 --><dependency><groupId>net.sf.eh…

Spring boot + mybatis plus 快速构建项目,生成基本业务操作代码。

---进行业务建表&#xff0c;这边根据个人业务分析&#xff0c;不具体操作 --加入mybatis plus pom依赖 <!-- mybatis-plus 3.0.5--> <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId>&l…

给手机浏览器减负 轻装上阵才能速度制胜

随着手机浏览器的发展&#xff0c;浏览器已经变得臃肿不堪&#xff0c;各种“功能”系于一身&#xff0c;有广告、社区、乐园等等&#xff0c;我们真的需要它们吗&#xff1f;如何才能让浏览器做到轻装上阵&#xff0c;又能高效满足我们需求呢&#xff1f; 过多“功能”的浏览器…

653. Two Sum IV - Input is a BST

题目来源&#xff1a; 自我感觉难度/真实难度&#xff1a; 题意&#xff1a; 分析&#xff1a; 自己的代码&#xff1a; class Solution(object):def findTarget(self, root, k):""":type root: TreeNode:type k: int:rtype: bool"""Allself.InO…

解决 dubbo问题:Forbid consumer 192.xx.xx.1 access service com.xx.xx.xx.rpc.api.xx from registry 116.xx1

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 我的情况是&#xff1a; 原本我把服务放在A工程中&#xff0c;后来改到B工程中了&#xff0c;所以原来的服务不存在了&#xff0c;查不…

vue学习:7、路由跳转

2019独角兽企业重金招聘Python工程师标准>>> <body><div id"app"></div></body><script type"text/javascript">var Login {template: <div>我是登陆界面</div>};var Register {template: <div…

Spring Retry 重试机制实现及原理

概要 Spring实现了一套重试机制&#xff0c;功能简单实用。Spring Retry是从Spring Batch独立出来的一个功能&#xff0c;已经广泛应用于Spring Batch,Spring Integration, Spring for Apache Hadoop等Spring项目。本文将讲述如何使用Spring Retry及其实现原理。 背景 重试&…

inline 内联函数详解 内联函数与宏定义的区别

一、在C&C中   一、inline 关键字用来定义一个类的内联函数&#xff0c;引入它的主要原因是用它替代C中表达式形式的宏定义。表达式形式的宏定义一例&#xff1a;#define ExpressionName(Var1,Var2) ((Var1)(Var2))*((Var1)-(Var2))为什么要取代这种形式呢&#xff0c;且…

Oracle序列更新为主键最大值

我们在使用 Oracle 数据库的时候&#xff0c;有时候会选择使用自增序列作为主键。但是在开发过程中往往会遇到一些不规范的操作&#xff0c;导致表的主键值不是使用序列插入的。这样在数据移植的时候就会出现各种各样的问题。当然数据库主键不使用序列是一种很好的方式&#xf…