安装Redis
https://www.jianshu.com/writer#/notebooks/21066443/notes/22422785
构建项目
- 访问地址:http://start.spring.io
- 添加Web、MySQL、JPA、Druid依赖
配置支持Redis
- 添加Redis依赖,添加缓存的支持需要两个依赖,一个是SpringBoot内部的缓存配置、另外则是redis缓存
org.springframework.boot
spring-boot-starter-cache
org.springframework.boot
spring-boot-starter-redis
1.4.7.RELEASE
- 配置Redis数据库
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8
username: root
password: 123456
#配置监控统计拦截的filters
filters: stat,wall,log4j
#最大活跃数
maxActive: 20
#初始化数量
initialSize: 1
#最大连接等待超时时间
maxWait: 60000
#打开PSCache,并指定每个连接PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
#通过connectionProperties属性打开mergeSql功能
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
minldle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableldleTimeMillis: 300000
validationQuery: select 1 from dual
testWhiledle: true
testOnBorrow: false
testOnReturn: false
jpa:
properties:
hibernate:
show_sql: true
format_sql: true
#配置redis数据库连接
redis:
host: 127.0.0.1
password: 123456
port: 6379
jedis:
pool:
max-idle: 20
min-idle: 1
max-active: 20
max-wait: 60000
lettuce:
pool:
max-idle: 20
min-idle: 1
max-active: 20
max-wait: 60000
database: 0 #默认是索引为的0的数据库
- 配置CacheManager
让SpringBoot内置的缓存框架使用Redis作为新的缓存,添加一个RedisConfiguration配置类
package com.gala.springdataJPA.conf;
import java.lang.reflect.Method;
import java.time.Duration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
/**
* Redis缓存配置
*/
@Configuration
@EnableCaching // 支持缓存注解
public class RedisConfiguration extends CachingConfigurerSupport {
/**
* 自定义生成key的规则
*/
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
// 格式化缓存key字符串
StringBuilder sb = new StringBuilder();
// 追加类名
sb.append(o.getClass().getName());
// 追加方法名
sb.append(method.getName());
// 遍历参数并且追加
for (Object obj : objects) {
sb.append(obj.toString());
}
System.out.println("调用Redis缓存Key : " + sb.toString());
return sb.toString();
}
};
}
/**
* 采用RedisCacheManager作为缓存管理器
*/
@Bean
CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
// 初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
// 设置CacheManager的值序列化方式为JdkSerializationRedisSerializer,但其实RedisCacheConfiguration默认就是使用StringRedisSerializer序列化key,JdkSerializationRedisSerializer序列化value,所以以下注释代码为默认实现
// ClassLoader loader = this.getClass().getClassLoader();
// JdkSerializationRedisSerializer jdkSerializer = new
// JdkSerializationRedisSerializer(loader);
// RedisSerializationContext.SerializationPair
使用Redis
- 建表
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(50) DEFAULT NULL COMMENT '名字',
`password` varchar(50) DEFAULT NULL COMMENT '密码',
`age` int(11) DEFAULT '0' COMMENT '年龄',
`address` varchar(200) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- 建实体
package com.gala.springdataJPA.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "t_user")
public class User implements Serializable {
private static final long serialVersionUID = -7686478838017943454L;
private Long id;
private String name;
private String password;
private Integer age;
private String address;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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;
}
}
- 建接口
package com.gala.springdataJPA.jpa;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import com.gala.springdataJPA.entity.User;
public interface UserDao extends JpaRepository, JpaSpecificationExecutor {
}
- 建业务类
@CacheConfig:该注解是用来开启声明的类参与缓存,如果方法内的@Cacheable注解没有添加key值,那么会自动使用cahceNames配置参数并且追加方法名。
@Cacheable:配置方法的缓存参数,可自定义缓存的key以及value。
package com.gala.springdataJPA.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.gala.springdataJPA.entity.User;
import com.gala.springdataJPA.jpa.UserDao;
@Service
@CacheConfig(cacheNames = "user")
@Transactional
public class UserService {
@Autowired
private UserDao userDao;
@Cacheable
public List list() {
return userDao.findAll();
}
}
- 建控制器
package com.gala.springdataJPA.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gala.springdataJPA.entity.User;
import com.gala.springdataJPA.service.UserService;
@RestController
public class UserRedisController {
@Autowired
private UserService userService;
/**
* 查询用户列表
*/
@RequestMapping(value = "/listUser")
public List listUser() {
return userService.list();
}
}
测试
启动项目,访问:127.0.0.1:8080/listUser
再次访问:127.0.0.1:8080/listUser