1.SpringBoot整合ehcache
pom.xml
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<groupId>per.czt</groupId>
<artifactId>23-spring-boot-ehcache</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>23-spring-boot-ehcache</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- junit环境的jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!-- druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.17</version>
</dependency>
<!-- jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.4</version>
</dependency>
<!-- jaxb-core -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<!-- jaxb-impl -->
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.1</version>
</dependency>
<!-- javax.activation-api -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
<version>1.2.0</version>
</dependency>
<!-- springboot 缓存支持启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Ehcache坐标 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
</dependencies>
</project>
ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="java.io.tmpdir" />
<!--defaultCache:echcache的默认缓存策略 -->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120"
maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</defaultCache>
<!-- 自定义缓存策略 -->
<cache name="usersCache" maxElementsInMemory="10000"
eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120"
maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
application.properties
spring.datasource.driverName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springbootjpa?serverTimezone=UTC&charset=UTF-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=200934652qwe
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.cache.ehcache.config=ehcache.xml
Users.java
package per.czt.pojo;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="t_users2")
public class Users implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="user_id")
private Integer userid;
@Column(name="user_name")
private String username;
@Column(name="user_age")
private Integer userage;
@Column(name="user_address")
private String useraddress;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getUserage() {
return userage;
}
public void setUserage(Integer userage) {
this.userage = userage;
}
public String getUseraddress() {
return useraddress;
}
public void setUseraddress(String useraddress) {
this.useraddress = useraddress;
}
public Users() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Users [userid=" + userid + ", username=" + username + ", userage=" + userage + ", useraddress="
+ useraddress + "]";
}
}
UsersService.java
package per.czt.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import per.czt.pojo.Users;
public interface UsersService {
public List<Users> findUsersAll();
public Users findUsersById(Integer userid);
public Page<Users> findUsersByPage(Pageable pageable);
public void saveUsers(Users users);
}
UsersServiceImpl.java
package per.czt.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import per.czt.dao.UsersRepository;
import per.czt.pojo.Users;
import per.czt.service.UsersService;
@Service
public class UsersServiceImpl implements UsersService{
@Autowired
private UsersRepository usersRespository;
@Override
@Cacheable(value="usersCache")
public List<Users> findUsersAll() {
// TODO Auto-generated method stub
return usersRespository.findAll();
}
/*
*
* @Cacheable:把方法的返回值添加到Ehcache中做缓存
* value:使用的缓存策略,如果没有指定,将使用默认的缓存策略
*/
@Override
@Cacheable(value="usersCache")//该方法启用缓存
public Users findUsersById(Integer userid) {
// TODO Auto-generated method stub
return usersRespository.findOne(userid);
}
@Override
@Cacheable(value="usersCache",key="#pageable.pageSize")//启用pageable下的pageSize作为缓存
public Page<Users> findUsersByPage(Pageable pageable) {
// TODO Auto-generated method stub
return usersRespository.findAll(pageable);
}
@Override
@CacheEvict(value="usersCache",allEntries=true)//销毁缓存
public void saveUsers(Users users) {
// TODO Auto-generated method stub
usersRespository.save(users);
}
}
UsersServiceTest.java
package per.czt.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import per.czt.pojo.Users;
import per.czt.service.UsersService;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={App.class})
public class UsersServiceTest {
@Autowired
private UsersService usersService;
/*@Test
public void testSaveUsers() {
Users users=new Users();
users.setUseraddress("上海市");
users.setUserage(21);
users.setUsername("Mike");
usersService.saveUsers(users);
}*/
@Test
public void testFindUsersById() {
System.out.println(usersService.findUsersById(1));
System.out.println(usersService.findUsersById(1));
}
@Test
public void testFindUsersByPage() {
Pageable pageable=new PageRequest(0, 2);
System.out.println("total:"+usersService.findUsersByPage(pageable).getTotalElements());
System.out.println("total:"+usersService.findUsersByPage(pageable).getTotalElements());
pageable=new PageRequest(1, 2);
System.out.println("total:"+usersService.findUsersByPage(pageable).getTotalElements());
}
@Test
public void testFindAll() {
System.out.println("size:"+usersService.findUsersAll().size());
Users users=new Users();
users.setUseraddress("广西省");
users.setUserage(23);
users.setUsername("Sarah");
usersService.saveUsers(users);
System.out.println("size:"+usersService.findUsersAll().size());
}
}
App.class
package per.czt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching//启用缓存
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
2.SpringBoot整合Redis
首先安装Redis,在命令行输入redis-server开启redis服务
pom.xml
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<groupId>per.czt</groupId>
<artifactId>24-spring-boot-reis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>25-spring-boot-redis</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- spring-boot启动器 -->
<!-- spring-boot就是一些jar包的集合,一共44个启动器 -->
<!-- spring-boot-start-web,支持全栈开发,包括tomcat和springmvc等 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
</project>
App.java
package per.czt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
User.java
package per.czt.pojo;
import java.io.Serializable;
//这里User类要实现Serializable接口
public class User implements Serializable{
private String userId;
private String userName;
private Integer userAge;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName + ", userAge=" + userAge + "]";
}
}
RedisConfig.java
package per.czt.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.databind.ser.std.StringSerializer;
import redis.clients.jedis.JedisPoolConfig;
/*
* 完成对redis整合的配置
*/
@Configuration
public class RedisConfig {
/*
* 1.创建JedisPoolConfig对象,在该对象中完成一些连接池的配置
*/
@Bean
@ConfigurationProperties(prefix="spring.redis.pool")//获取application.properties中前缀为spring.redis.pool的值
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
/*jedisPoolConfig.setMaxIdle(10);
jedisPoolConfig.setMinIdle(5);
jedisPoolConfig.setMaxTotal(20);*/
System.out.println("默认值:"+jedisPoolConfig.getMaxIdle());
System.out.println("默认值:"+jedisPoolConfig.getMinIdle());
System.out.println("默认值:"+jedisPoolConfig.getMaxTotal());
return jedisPoolConfig;
}
/*
* 2.创建JedisConnectionFactory,配置redis链接信息
*/
@Bean
@ConfigurationProperties(prefix="spring.redis")
public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig poolConfig) {
System.out.println("配置值:"+poolConfig.getMaxIdle());
System.out.println("配置值:"+poolConfig.getMinIdle());
System.out.println("配置值:"+poolConfig.getMaxTotal());
JedisConnectionFactory jedisConnectionFactory=new JedisConnectionFactory();
//配置连接池对象
jedisConnectionFactory.setPoolConfig(poolConfig);
//配置redis信息
return jedisConnectionFactory;
}
/*
* 3.创建RedisTemplate:用于执行redis操作的方法
*/
@Bean
public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory){
System.out.println("hostName:"+factory.getHostName());
System.out.println("port:"+factory.getPort());
RedisTemplate<String,Object> redisTemplate=new RedisTemplate<String, Object>();
//关联
redisTemplate.setConnectionFactory(factory);
//为key设置序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
//为value设置序列化器
redisTemplate.setValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
}
application.properties
spring.redis.pool.max-idle=10
spring.redis.pool.min-idle=5
spring.redis.pool.max-total=20
spring.redis.hostName=127.0.0.1
spring.redis.port=6379
RedisTest.java
package per.czt;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import per.czt.pojo.User;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { App.class })
public class RedisTest {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/*
* 添加一个字符串
*/
/*
* @Test public void test1() {
*
* redisTemplate.opsForValue().set("str", "Hello,Redis"); }
*/
/*
* 获取一个字符串
*
*/
@Test
public void test2() {
System.out.println(redisTemplate.opsForValue().get("str"));
}
/*
* 添加对象
*/
/*
* @Test public void test3() {
*
* User users=new User(); users.setUserAge(12); users.setUserName("江云");
*
* redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
* redisTemplate.opsForValue().set("users", users); }
*/
/*
* 取出users对象
*
*/
@Test
public void test4() {
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
System.out.println(redisTemplate.opsForValue().get("users"));
}
/*
* 以json格式存储对象
*
*/
@Test
public void test5() {
User users = new User();
users.setUserAge(14);
users.setUserName("江民");
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(User.class));
redisTemplate.opsForValue().set("users1", users);
}
/*
* 取出json格式存储的对象
*/
@Test
public void test6() {
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(User.class));
System.out.println(redisTemplate.opsForValue().get("users1"));
}
}