引用的是Spring-data-redis:1.8.4
关于spring-redis
spring-data-redis针对jedis提供了如下功能:
1. 连接池自动管理,提供了一个高度封装的“RedisTemplate”类
2. 针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口
ValueOperations:简单K-V操作
SetOperations:set类型数据操作
ZSetOperations:zset类型数据操作
HashOperations:针对map类型的数据操作
ListOperations:针对list类型的数据操作
4. 将事务操作封装,有容器控制
springboot 与redis的整合
pom文件
依赖如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!-- spring boot 配置 -->
<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>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
application.properties
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
/**
* 设置key的生命周期
*
* @param key
* @param time
* @param timeUnit
*/
public void expireKey(String key, long time, TimeUnit timeUnit) {
redisTemplate.expire(key, time, timeUnit);
}
redisTemplate的配置
新建一个redisConfig类,进行相关bean的配置:
package com.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author janti
* reids 相关bean的配置
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* 选择redis作为默认缓存工具
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
return rcm;
}
/**
* retemplate相关配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
/**
* 对hash类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 对redis字符串类型数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对链表类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对无序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对有序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
spring-redis中使用了RedisTemplate来进行redis的操作,通过泛型的K和V设置键值对的对象类型。这里使用了string作为key的对象类型,值为Object。
-
对于Object,spring-redis默认使用了jdk自带的序列化,不推荐使用默认了。所以使用了json的序列化方式
- 对spring-redis对redis的五种数据类型也有支持
- HashOperations:对hash类型的数据操作
- ValueOperations:对redis字符串类型数据操作
- ListOperations:对链表类型的数据操作
- SetOperations:对无序集合类型的数据操作
-
ZSetOperations:对有序集合类型的数据操作
redis操作的工具类
package com.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Component
public class RedisService {
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 默认过期时长,单位:秒
*/
public static final long DEFAULT_EXPIRE = 60 * 60 * 24;
/**
* 不设置过期时长
*/
public static final long NOT_EXPIRE = -1;
public boolean existsKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 重名名key,如果newKey已经存在,则newKey的原值被覆盖
*
* @param oldKey
* @param newKey
*/
public void renameKey(String oldKey, String newKey) {
redisTemplate.rename(oldKey, newKey);
}
/**
* newKey不存在时才重命名
*
* @param oldKey
* @param newKey
* @return 修改成功返回true
*/
public boolean renameKeyNotExist(String oldKey, String newKey) {
return redisTemplate.renameIfAbsent(oldKey, newKey);
}
/**
* 删除key
*
* @param key
*/
public void deleteKey(String key) {
redisTemplate.delete(key);
}
/**
* 删除多个key
*
* @param keys
*/
public void deleteKey(String... keys) {
Set<String> kSet = Stream.of(keys).map(k -> k).collect(Collectors.toSet());
redisTemplate.delete(kSet);
}
/**
* 删除Key的集合
*
* @param keys
*/
public void deleteKey(Collection<String> keys) {
Set<String> kSet = keys.stream().map(k -> k).collect(Collectors.toSet());
redisTemplate.delete(kSet);
}
/**
* 设置key的生命周期
*
* @param key
* @param time
* @param timeUnit
*/
public void expireKey(String key, long time, TimeUnit timeUnit) {
redisTemplate.expire(key, time, timeUnit);
}
/**
* 指定key在指定的日期过期
*
* @param key
* @param date
*/
public void expireKeyAt(String key, Date date) {
redisTemplate.expireAt(key, date);
}
/**
* 查询key的生命周期
*
* @param key
* @param timeUnit
* @return
*/
public long getKeyExpire(String key, TimeUnit timeUnit) {
return redisTemplate.getExpire(key, timeUnit);
}
/**
* 将key设置为永久有效
*
* @param key
*/
public void persistKey(String key) {
redisTemplate.persist(key);
}
}
redis的key工具类
package com.util;
/**
* redisKey设计
*/
public class RedisKeyUtil {
/**
* redis的key
* 形式为:
* 表名:主键名:主键值:列名
*
* @param tableName 表名
* @param majorKey 主键名
* @param majorKeyValue 主键值
* @param column 列名
* @return
*/
public static String getKeyWithColumn(String tableName,String majorKey,String majorKeyValue,String column){
StringBuffer buffer = new StringBuffer();
buffer.append(tableName).append(":");
buffer.append(majorKey).append(":");
buffer.append(majorKeyValue).append(":");
buffer.append(column);
return buffer.toString();
}
/**
* redis的key
* 形式为:
* 表名:主键名:主键值
*
* @param tableName 表名
* @param majorKey 主键名
* @param majorKeyValue 主键值
* @return
*/
public static String getKey(String tableName,String majorKey,String majorKeyValue){
StringBuffer buffer = new StringBuffer();
buffer.append(tableName).append(":");
buffer.append(majorKey).append(":");
buffer.append(majorKeyValue).append(":");
return buffer.toString();
}
}
如何使用?
测试代码
新建一个实体类:
package com.domain;
public class UserVo {
public static final String Table = "t_user";
private String name;
private String address;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "UserVo{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}
再新建一个测试类:
package com.config;
import com.domain.UserVo;
import com.service.RedisService;
import com.util.RedisKeyUtil;
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.*;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisConfigTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Resource
private ValueOperations<String,Object> valueOperations;
@Autowired
private HashOperations<String, String, Object> hashOperations;
@Autowired
private ListOperations<String, Object> listOperations;
@Autowired
private SetOperations<String, Object> setOperations;
@Autowired
private ZSetOperations<String, Object> zSetOperations;
@Resource
private RedisService redisService;
@Test
public void testObj() throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("上海");
userVo.setName("测试dfas");
userVo.setAge(123);
ValueOperations<String,Object> operations = redisTemplate.opsForValue();
redisService.expireKey("name",20, TimeUnit.SECONDS);
String key = RedisKeyUtil.getKey(UserVo.Table,"name",userVo.getName());
UserVo vo = (UserVo) operations.get(key);
System.out.println(vo);
}
@Test
public void testValueOption( )throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("上海");
userVo.setName("jantent");
userVo.setAge(23);
valueOperations.set("test",userVo);
System.out.println(valueOperations.get("test"));
}
@Test
public void testSetOperation() throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("北京");
userVo.setName("jantent");
userVo.setAge(23);
UserVo auserVo = new UserVo();
auserVo.setAddress("n柜昂周");
auserVo.setName("antent");
auserVo.setAge(23);
setOperations.add("user:test",userVo,auserVo);
Set<Object> result = setOperations.members("user:test");
System.out.println(result);
}
@Test
public void HashOperations() throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("北京");
userVo.setName("jantent");
userVo.setAge(23);
hashOperations.put("hash:user",userVo.hashCode()+"",userVo);
System.out.println(hashOperations.get("hash:user",userVo.hashCode()+""));
}
@Test
public void ListOperations() throws Exception{
UserVo userVo = new UserVo();
userVo.setAddress("北京");
userVo.setName("jantent");
userVo.setAge(23);
// listOperations.leftPush("list:user",userVo);
// System.out.println(listOperations.leftPop("list:user"));
// pop之后 值会消失
System.out.println(listOperations.leftPop("list:user"));
}
}
注解缓存的使用
-
@Cacheable:在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;没有则调用方法并将方法返回值放进缓存。
-
@CachePut:将方法的返回值放到缓存中。
-
@CacheEvict:删除缓存中的数据。
Spring Cache 和 redis 使用
spring Cache
是Spring
框架提供的对缓存使用的抽象类,支持多种缓存,比如Redis
、EHCache
等,集成很方便。同时提供了多种注解来简化缓存的使用,可对方法进行缓存。
修改RedisConfig
配置类,加入注解@EnableCaching
,同时设置CacheManager
缓存管理类,这里使用RedisCacheManager
,其他的管理类还有:SimpleCacheManager
、ConcurrentMapCacheManager
等,默认提供的在类org.springframework.cache.support
下,可自行查阅。
/**
*
* @author oKong
*
*/
@Configuration
@EnableCaching
public class RedisConfig {
/**
* 定义 StringRedisTemplate ,指定序列号和反序列化的处理类
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//序列化 值时使用此序列化方法
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public CacheManager cacheManager(RedisTemplate<String,String> redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//使用前缀
rcm.setUsePrefix(true);
//缓存分割符 默认为 ":"
// rcm.setCachePrefix(new DefaultRedisCachePrefix(":"));
//设置缓存过期时间
//rcm.setDefaultExpiration(60);//秒
return rcm;
}
}
1.改造UserController
控制层,引入@Cacheable
等注解。
/**
* 用户控制层 简单演示增删改查及分页
* 新增了swagger文档内容 2018-07-21
* 新增了@caching使用 2018-07-23
* @author oKong
*
*/
@RestController
@RequestMapping("/user")
@Api(tags="用户API")
public class UserController {
@Autowired
IUserService userService;
@PostMapping("add")
@ApiOperation(value="用户新增")
//正常业务时, 需要在user类里面进行事务控制,控制层一般不进行业务控制的。
//@Transactional(rollbackFor = Exception.class)
public Map<String,String> addUser(@Valid @RequestBody UserReq userReq){
User user = new User();
user.setCode(userReq.getCode());
user.setName(userReq.getName());
//由于设置了主键策略 id可不用赋值 会自动生成
//user.setId(0L);
userService.insert(user);
Map<String,String> result = new HashMap<String,String>();
result.put("respCode", "01");
result.put("respMsg", "新增成功");
//事务测试
//System.out.println(1/0);
return result;
}
@PostMapping("update")
@ApiOperation(value="用户修改")
//更新时 直接删除缓存 以保证下次获取时先从数据库中获取最新数据
@CacheEvict(value="OKONG", key="#userReq.id")
public Map<String,String> updateUser(@Valid @RequestBody UserReq userReq){
if(userReq.getId() == null || "".equals(userReq.getId())) {
throw new CommonException("0000", "更新时ID不能为空");
}
User user = new User();
user.setCode(userReq.getCode());
user.setName(userReq.getName());
user.setId(Long.parseLong(userReq.getId()));
userService.updateById(user);
Map<String,String> result = new HashMap<String,String>();
result.put("respCode", "01");
result.put("respMsg", "更新成功");
return result;
}
@GetMapping("/get/{id}")
@ApiOperation(value="用户查询(ID)")
@ApiImplicitParam(name="id",value="查询ID",required=true)
@Cacheable(value="OKONG",key="#id")
public Map<String,Object> getUser(@PathVariable("id") String id){
//查询
User user = userService.selectById(id);
if(user == null) {
throw new CommonException("0001", "用户ID:" + id + ",未找到");
}
UserResp resp = UserResp.builder()
.id(user.getId().toString())
.code(user.getCode())
.name(user.getName())
.status(user.getStatus())
.build();
Map<String,Object> result = new HashMap<String,Object>();
result.put("respCode", "01");
result.put("respMsg", "成功");
result.put("data", resp);
return result;
}
@GetMapping("/page")
@ApiOperation(value="用户查询(分页)")
public Map<String,Object> pageUser(int current, int size){
//分页
Page<User> page = new Page<>(current, size);
Map<String,Object> result = new HashMap<String,Object>();
result.put("respCode", "01");
result.put("respMsg", "成功");
result.put("data", userService.selectPage(page));
return result;
}
2.利用Swagger
控制页面,新增一个用户,然后获取用户,会发现缓存里已经有此id的用户数据了。
再次获取,会发现这次没有直接访问数据库了,而是直接从缓存读取。大家可在观察下控制台的输出情况(可先清空控制台,然后在请求)。
此时控制台无任何输出,但前端已经获取到值了。
关于SpringCache 注解的简单介绍
- @Cacheable:标记在一个方法上,也可以标记在一个类上。主要是缓存标注对象的返回结果,标注在方法上缓存该方法的返回值,标注在类上,缓存该类所有的方法返回值。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件
- @CacheEvict:从缓存中移除相应数据。
- @CachePut:方法支持缓存功能。与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
redisTemplate操作字符串、操作hash、操作list、操作set、操作有序set
- @Caching:多个Cache注解使用,比如新增用户时,删除用户属性等需要删除或者更新多个缓存时,集合以上三个注解。
redisTemplate.opsForValue(); //操作字符串
redisTemplate.opsForHash(); //操作hash
redisTemplate.opsForList(); //操作list
redisTemplate.opsForSet(); //操作set
redisTemplate.opsForZSet(); //操作有序set
例如:
stringRedisTemplate.opsForValue().get("test")// 根据 key 获取缓存中的 val
stringRedisTemplate.boundValueOps("test").increment(1);//val +1
stringRedisTemplate.opsForSet().add("red_123", "1","2","3");// 向指定 key 中存放 set 集合
作者:sologxl
链接:https://hacpai.com/article/1544767236385
来源:黑客派
协议:CC BY-SA 4.0 https://creativecommons.org/licenses/by-sa/4.0/
转载于:https://www.cnblogs.com/superfj/p/9232482.html
http://www.importnew.com/29554.html