概述
Redis是一款高性能key-value數(shù)據(jù)庫,有豐富的數(shù)據(jù)類型string爬骤、list趴久、hash、set塘辅、zset绝页。
常用的應用場景
緩存荠商、消息隊列、session共享续誉、分布式ID莱没、分布式鎖、關注/點贊酷鸦、排行榜等等,我們這篇主要來講緩存的應用
開始在SpringBoot項目中實踐
- redis的安裝本篇不做闡述,后續(xù)可以補充
- redis可視化工具可以自行選擇安裝,這里使用Redis Desktop Manager,也可以選擇RedisStudio
- 本篇在之前JPA的項目基礎上,我們加以改造,加入redis緩存操作
- 現(xiàn)在pom.xml中加入redis依賴
<!-- redis 緩存操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
- 在yml配置文件中加入redis配置信息
spring:
redis:
database: 0 # Redis數(shù)據(jù)庫索引(默認為0)
host: localhost # Redis服務器地址
port: 6379 # Redis服務器連接端口
password: # Redis服務器連接密碼(默認為空)
lettuce:
pool:
max-active: 8 # 連接池最大連接數(shù)(使用負值表示沒有限制) 默認 8
max-wait: -1 # 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1
max-idle: 8 # 連接池中的最大空閑連接 默認 8
min-idle: 0 # 連接池中的最小空閑連接 默認 0
cache:
type: redis
在SpringBoot2.X,redis默認使用lettuce,基于Netty性能高于以前的jedis饰躲。
- 創(chuàng)建RedisConfig.java配置類
package com.zhlab.demo.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @ClassName RedisConfig
* @Description //Redis緩存配置類
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2020/11/3 0003 下午 2:15
**/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Bean
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
// 配置連接工廠
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
// 指定要序列化的域牙咏,field,get和set,以及修飾符范圍,ANY是都有包括private和public
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化輸入的類型嘹裂,類必須是非final修飾的妄壶,final修飾的類,比如String,Integer等會跑出異常
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(mapper);
// 值采用json序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
// 使用StringRedisSerializer來序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 設置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
- DAO層不變,按之前的SysAdminUserRepository.java
public interface SysAdminUserRepository extends JpaRepository<SysAdminUser,Long>, Serializable {
// 就這么簡單?
// 對,就這么簡單,什么都不用寫,這是Spring Data JPA 默認幫我們實現(xiàn)了基本的數(shù)據(jù)庫操作
// 如果需要擴展,可以自定義符合Spring Data JPA規(guī)則的查詢方法寄狼,由框架將其自動解析為SQL
}
- Service層中加入緩存注解@CacheConfig丁寄、@Cacheable、@CachePut泊愧、@CacheEvict,SysAdminUserService.java,
package com.zhlab.demo.service;
import com.zhlab.demo.dao.SysAdminUserRepository;
import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.utils.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName SysAdminUserService
* @Description //SysAdminUserService
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2020/10/31 0031 上午 9:45
**/
@CacheConfig(cacheNames = "users")
@Service
public class SysAdminUserService {
@Autowired
SysAdminUserRepository sysAdminUserRepository;
@Cacheable(key="'user_'+#userId")
public SysAdminUser findUser(Long userId){
return sysAdminUserRepository.findById(userId).orElse(null);
}
@CachePut(key="'user_'+#result.adminUserId")
public SysAdminUser save(SysAdminUser user){
return sysAdminUserRepository.save(user);
}
@CacheEvict(key="'user_'+#userId")
public void deleteUser(Long userId) {
sysAdminUserRepository.findById(userId).ifPresent(sysAdminUserRepository::delete);
}
}
- 接口層,UserController.java 加入增伊磺、刪、查來測試一下
package com.zhlab.demo.controller;
import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.service.SysAdminUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @ClassName UserController
* @Description //用戶接口層
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2020/10/31 0031 上午 9:43
**/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
SysAdminUserService sysAdminUserService;
@ApiOperation(value = "方法名:用戶信息", notes = "獲取用戶信息")
@GetMapping("/{userId}")
public SysAdminUser findUser(@PathVariable Long userId){
return sysAdminUserService.findUser(userId);
}
@ApiOperation(value = "方法名:新增用戶", notes = "新增用戶")
@PostMapping("/add")
public SysAdminUser addUser(@RequestBody SysAdminUser user){
return sysAdminUserService.save(user);
}
@ApiOperation(value = "方法名:刪除用戶信息", notes = "刪除用戶信息")
@GetMapping("/delete/{userId}")
public void deleteUser(@PathVariable Long userId){
sysAdminUserService.deleteUser(userId);
}
}
- 啟動項目,打開http://localhost:8080/swagger-ui.html來調試接口
redisManager中,可以看到現(xiàn)在redis里現(xiàn)在還沒數(shù)據(jù)
-
調試一下查詢userId=1的用戶信息
此時查看一下redis中的數(shù)據(jù),已經(jīng)新增了一條緩存數(shù)據(jù)
之后查詢這用戶,數(shù)據(jù)會從緩存中獲取删咱。
新增屑埋、刪除調試方法類同。
9.接下來再增加另一種,通過redisTemplate來操作緩存數(shù)據(jù),修改之前的UserController.java痰滋,
package com.zhlab.demo.controller;
import com.zhlab.demo.model.SysAdminUser;
import com.zhlab.demo.service.SysAdminUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;
/**
* @ClassName UserController
* @Description //用戶接口層
* @Author singleZhang
* @Email 405780096@qq.com
* @Date 2020/10/31 0031 上午 9:43
**/
@RestController
@RequestMapping("/user")
public class UserController {
private static final int expireTime = 30;
@Autowired
SysAdminUserService sysAdminUserService;
@Autowired
RedisTemplate redisTemplate;
@ApiOperation(value = "方法名:用戶信息", notes = "獲取用戶信息")
@GetMapping("/{userId}")
public SysAdminUser findUser(@PathVariable Long userId){
//從緩存獲取有無這個用戶信息
SysAdminUser userInfo = getCacheObject("users::user_"+userId);
if(userInfo == null){
//沒有,則從數(shù)據(jù)庫查詢
userInfo =sysAdminUserService.findUser(userId);
//設置緩存
setCacheObject("users::user_"+userId,userInfo,expireTime,TimeUnit.MINUTES);
}
return sysAdminUserService.findUser(userId);
}
@ApiOperation(value = "方法名:新增用戶", notes = "新增用戶")
@PostMapping("/add")
public SysAdminUser addUser(@RequestBody SysAdminUser user){
return sysAdminUserService.save(user);
}
@ApiOperation(value = "方法名:刪除用戶信息", notes = "刪除用戶信息")
@GetMapping("/delete/{userId}")
public void deleteUser(@PathVariable Long userId){
sysAdminUserService.deleteUser(userId);
}
/**
* 獲取緩存
* */
private <T> T getCacheObject(String key){
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 設置緩存
* */
private <T> ValueOperations<String, T> setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit) {
ValueOperations<String, T> operation = redisTemplate.opsForValue();
operation.set(key, value, timeout, timeUnit);
return operation;
}
}
-
繼續(xù)來調試/user/{userId}這個接口
查看結果
總結
SpringBoot中使用redis緩存的方法就介紹到這兒,需要熟練掌握,因為大型項目中緩存的應用非常廣泛雀彼。