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.pswp.cn/news/450287.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/450287.shtml
英文地址,請注明出處:http://en.pswp.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…