青岛网站seo技巧,福田网站建设信科网络,手机网站建设一般多少钱,免费seo优化工具前些天发现了一个巨牛的人工智能学习网站#xff0c;通俗易懂#xff0c;风趣幽默#xff0c;忍不住分享一下给大家。点击跳转到教程。
我门知道一个程序的瓶颈在于数据库#xff0c;我门也知道内存的速度是大大快于硬盘的速度的。当我门需要重复的获取相同的数据的时候通俗易懂风趣幽默忍不住分享一下给大家。点击跳转到教程。
我门知道一个程序的瓶颈在于数据库我门也知道内存的速度是大大快于硬盘的速度的。当我门需要重复的获取相同的数据的时候我门一次又一次的请求数据库或者远程服务导致大量的时间耗费在数据库查询或者远程方法的调用上导致程序性能的恶化这更是数据缓存要解决的问题。
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开启缓存支持即可。 小例子
小例子是使用 springbootjpa cache 实现的。
实例步骤目录
1.创建maven项目2.数据库配置3.jpa配置和cache配置4.编写bean 和dao层5.编写service层6.编写controller7.启动cache8.测试校验1.创建maven项目
新建maven 项目pom.xml文件如下内容如下
?xml version1.0 encodingUTF-8?
project xmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdcom.us/groupIdartifactIdspringboot-Cache/artifactIdversion1.0-SNAPSHOT/versionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion1.3.0.RELEASE/version/parentpropertiesstart-classcom.us.Application/start-classmaven.compiler.target1.8/maven.compiler.targetmaven.compiler.source1.8/maven.compiler.source/properties!-- Add typical dependencies for a web application --dependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-cache/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-jpa/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdnet.sf.ehcache/groupIdartifactIdehcache/artifactId/dependency!--db--dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion6.0.5/version/dependencydependencygroupIdcom.mchange/groupIdartifactIdc3p0/artifactIdversion0.9.5.2/versionexclusionsexclusiongroupIdcommons-logging/groupIdartifactIdcommons-logging/artifactId/exclusion/exclusions/dependency/dependencies/project
2.数据库配置
在src/main/esouces目录下新建application.properties 文件内容为数据库连接信息如下 application.properties
ms.db.driverClassNamecom.mysql.jdbc.Driver
ms.db.urljdbc:mysql://localhost:3306/cache?prepStmtCacheSize517cachePrepStmtstrueautoReconnecttrueuseUnicodetruecharacterEncodingutf-8useSSLfalseallowMultiQueriestrue
ms.db.usernameroot
ms.db.passwordxxxxxx
ms.db.maxActive500
新建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(namedataSource)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配置
springdata 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);MapString, 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 {IdGeneratedValueprivate 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 JpaRepositoryPerson, 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的idCachePut(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?nameabelage23addressshanghaiRequestMapping(/put)public Person put(Person person){return demoService.save(person);}//http://localhost:8080/able?id1RequestMapping(/able)ResponseBodypublic Person cacheable(Person person){return demoService.findOne(person);}//http://localhost:8080/evit?id1RequestMapping(/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?id1首先要在数据库中初始化几条数据。 控制台输出 “为id、key为:1数据做了缓存“ 此时已经为此次查询做了缓存再次查询该条数据将不会出现此条语句也就是不查询数据库了。
检验put
在浏览器输入http://localhost:8080/put?nameabelage23addressshanghai向数据库插入一条数据并将数据放入缓存。 此时控制台输出为该条记录做了缓存 然后再次调用able 方法查询该条数据将不再查询数据库直接从缓存中读取数据。
测试evit
在浏览器输入http://localhost:8080/evit?id1将该条记录从缓存中清楚清除后在次访问该条记录将会重新将该记录放入缓存。
控制台输出 切换缓存
1.切换为EhCache作为缓存
pom.xml 文件中添加依赖
dependencygroupIdnet.sf.ehcache/groupIdartifactIdehcache/artifactId/dependency
在resource 文件夹下新建ehcache的配置文件ehcache.xml 内容如下此文件spring boot 会自动扫描
?xml version1.0 encodingUTF-8?
ehcache!--切换为ehcache 缓存时使用--
cache namepeople maxElementsInMemory1000 /
/ehcache
2.切换为Guava作为缓存
只需要在pom中添加依赖 dependencygroupIdcom.google.guava/groupIdartifactIdguava/artifactIdversion18.0/version/dependency
3.切换为redis作为缓存
请看下篇博客
本文参考《JavaEE开发的颠覆者Spring Boot实战 》
本文源代码https://github.com/527515025/springBoot.git 见http://blog.csdn.net/u012373815/article/details/54564076