SpringBoot結(jié)合Redis實(shí)現(xiàn)接口冪等性的示例代碼
介紹
冪等性的概念是,任意多次執(zhí)行所產(chǎn)生的影響都與一次執(zhí)行產(chǎn)生的影響相同,按照這個(gè)含義,最終的解釋是對(duì)數(shù)據(jù)庫的影響只能是一次性的,不能重復(fù)處理。手段如下
- 數(shù)據(jù)庫建立唯一索引
- token機(jī)制
- 悲觀鎖或者是樂觀鎖
- 先查詢后判斷
小小主要帶你們介紹Redis實(shí)現(xiàn)自動(dòng)冪等性。其原理如下圖所示。

實(shí)現(xiàn)過程
引入 maven 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>spring 配置文件寫入
server.port=8080 core.datasource.druid.enabled=true core.datasource.druid.url=jdbc:mysql://192.168.1.225:3306/?useUnicode=true&characterEncoding=UTF-8 core.datasource.druid.username=root core.datasource.druid.password= core.redis.enabled=true spring.redis.host=192.168.1.225 #本機(jī)的redis地址 spring.redis.port=16379 spring.redis.database=3 spring.redis.jedis.pool.max-active=10 spring.redis.jedis.pool.max-idle=10 spring.redis.jedis.pool.max-wait=5s spring.redis.jedis.pool.min-idle=10
引入 Redis
引入 Spring boot 中的redis相關(guān)的stater,后面需要用到 Spring Boot 封裝好的 RedisTemplate
package cn.smallmartial.demo.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* @Author smallmartial
* @Date 2020/4/16
* @Email smallmarital@qq.com
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
/**
* 寫入緩存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 寫入緩存設(shè)置時(shí)間
*
* @param key
* @param value
* @param expireTime
* @return
*/
public boolean setEx(final String key, Object value, long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 讀取緩存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 刪除對(duì)應(yīng)的value
*
* @param key
*/
public boolean remove(final String key) {
if (exists(key)) {
Boolean delete = redisTemplate.delete(key);
return delete;
}
return false;
}
/**
* 判斷key是否存在
*
* @param key
* @return
*/
public boolean exists(final String key) {
boolean result = false;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
if (Objects.nonNull(operations.get(key))) {
result = true;
}
return result;
}
}自定義注解
自定義一個(gè)注解,定義此注解的目的是把它添加到需要實(shí)現(xiàn)冪等的方法上,只要某個(gè)方法注解了其,都會(huì)自動(dòng)實(shí)現(xiàn)冪等操作。其代碼如下
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIdempotent {
}token 的創(chuàng)建和實(shí)現(xiàn)
token 服務(wù)接口,我們新建一個(gè)接口,創(chuàng)建token服務(wù),里面主要是有兩個(gè)方法,一個(gè)用來創(chuàng)建 token,一個(gè)用來驗(yàn)證token
public interface TokenService {
/**
* 創(chuàng)建token
* @return
*/
public String createToken();
/**
* 檢驗(yàn)token
* @param request
* @return
*/
public boolean checkToken(HttpServletRequest request) throws Exception;
}token 的實(shí)現(xiàn)類,token中引用了服務(wù)的實(shí)現(xiàn)類,token引用了 redis 服務(wù),創(chuàng)建token采用隨機(jī)算法工具類生成隨機(jī) uuid 字符串,然后放入 redis 中,如果放入成功,返回token,校驗(yàn)方法就是從 header 中獲取 token 的值,如果不存在,直接跑出異常,這個(gè)異常信息可以被直接攔截到,返回給前端。
package cn.smallmartial.demo.service.impl;
import cn.smallmartial.demo.bean.RedisKeyPrefix;
import cn.smallmartial.demo.bean.ResponseCode;
import cn.smallmartial.demo.exception.ApiResult;
import cn.smallmartial.demo.exception.BusinessException;
import cn.smallmartial.demo.service.TokenService;
import cn.smallmartial.demo.utils.RedisUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;
import java.util.UUID;
/**
* @Author smallmartial
* @Date 2020/4/16
* @Email smallmarital@qq.com
*/
@Service
public class TokenServiceImpl implements TokenService {
@Autowired
private RedisUtil redisService;
/**
* 創(chuàng)建token
*
* @return
*/
@Override
public String createToken() {
String str = UUID.randomUUID().toString().replace("-", "");
StringBuilder token = new StringBuilder();
try {
token.append(RedisKeyPrefix.TOKEN_PREFIX).append(str);
redisService.setEx(token.toString(), token.toString(), 10000L);
boolean empty = StringUtils.isEmpty(token.toString());
if (!empty) {
return token.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* 檢驗(yàn)token
*
* @param request
* @return
*/
@Override
public boolean checkToken(HttpServletRequest request) throws Exception {
String token = request.getHeader(RedisKeyPrefix.TOKEN_NAME);
if (StringUtils.isEmpty(token)) {// header中不存在token
token = request.getParameter(RedisKeyPrefix.TOKEN_NAME);
if (StringUtils.isEmpty(token)) {// parameter中也不存在token
throw new BusinessException(ApiResult.BADARGUMENT);
}
}
if (!redisService.exists(token)) {
throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
}
boolean remove = redisService.remove(token);
if (!remove) {
throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
}
return true;
}
}攔截器的配置
用于攔截前端的 token,判斷前端的 token 是否有效
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Bean
public AuthInterceptor authInterceptor() {
return new AuthInterceptor();
}
/**
* 攔截器配置
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor());
// .addPathPatterns("/ksb/**")
// .excludePathPatterns("/ksb/auth/**", "/api/common/**", "/error", "/api/*");
super.addInterceptors(registry);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}攔截處理器:主要用于攔截掃描到 Autoldempotent 到注解方法,然后調(diào)用 tokenService 的 checkToken 方法校驗(yàn) token 是否正確,如果捕捉到異常就把異常信息渲染成 json 返回給前端。這部分代碼主要和自定義注解部分掛鉤。其主要代碼如下所示
@Slf4j
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Autowired
private TokenService tokenService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
//被ApiIdempotment標(biāo)記的掃描
AutoIdempotent methodAnnotation = method.getAnnotation(AutoIdempotent.class);
if (methodAnnotation != null) {
try {
return tokenService.checkToken(request);// 冪等性校驗(yàn), 校驗(yàn)通過則放行, 校驗(yàn)失敗則拋出異常, 并通過統(tǒng)一異常處理返回友好提示
} catch (Exception ex) {
throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
}
}
return true;
}
}測試用例
這里進(jìn)行相關(guān)的測試用例 模擬業(yè)務(wù)請求類,通過相關(guān)的路徑獲得相關(guān)的token,然后調(diào)用 testidempotence 方法,這個(gè)方法注解了 @Autoldempotent,攔截器會(huì)攔截所有的請求,當(dāng)判斷到處理的方法上面有該注解的時(shí)候,就會(huì)調(diào)用 TokenService 中的 checkToken() 方法,如果有異常會(huì)跑出,代碼如下所示
/**
* @Author smallmartial
* @Date 2020/4/16
* @Email smallmarital@qq.com
*/
@RestController
public class BusinessController {
@Autowired
private TokenService tokenService;
@GetMapping("/get/token")
public Object getToken(){
String token = tokenService.createToken();
return ResponseUtil.ok(token) ;
}
@AutoIdempotent
@GetMapping("/test/Idempotence")
public Object testIdempotence() {
String token = "接口冪等性測試";
return ResponseUtil.ok(token) ;
}
}用瀏覽器進(jìn)行訪問

用獲取到的token第一次訪問

用獲取到的token再次訪問

可以看到,第二次訪問失敗,即,冪等性驗(yàn)證通過。
到此這篇關(guān)于SpringBoot結(jié)合Redis實(shí)現(xiàn)接口冪等性的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot Redis接口冪等性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis Map結(jié)果的Key轉(zhuǎn)為駝峰式
今天小編就為大家分享一篇關(guān)于MyBatis Map結(jié)果的Key轉(zhuǎn)為駝峰式,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-12-12
解析Spring RestTemplate必須搭配MultiValueMap的理由
本文給大家介紹Spring RestTemplate必須搭配MultiValueMap的理由,本文通過實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-11-11
Java SpringBoot微服務(wù)框架驗(yàn)證碼報(bào)錯(cuò)問題解決方案
這篇文章主要介紹了Java SpringBoot微服務(wù)框架驗(yàn)證碼報(bào)錯(cuò)問題解決方案,包括dockerfile容器操作和完整dockerfile,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-08-08
java 學(xué)習(xí)筆記(入門篇)_程序流程控制結(jié)構(gòu)和方法
程序流程控制結(jié)構(gòu)分為:順序、選擇、循環(huán)以及異常處理結(jié)構(gòu),語句是程序的基本組成單位,一般來說語句的執(zhí)行流程是按順序來進(jìn)行的,但是當(dāng)遇到一些特殊的條件,比如循環(huán),這時(shí)候語句就會(huì)按照流程控制結(jié)構(gòu)來進(jìn)行了2013-01-01
jmeter接口測試教程及接口測試流程詳解(全網(wǎng)僅有)
Jmeter是由Apache公司開發(fā)的一個(gè)純Java的開源項(xiàng)目,即可以用于做接口測試也可以用于做性能測試。本文給大家分享jmeter接口測試教程及接口測試流程,感興趣的朋友跟隨小編一起看看吧2021-12-12
Java多線程并發(fā)編程(互斥鎖Reentrant Lock)
這篇文章主要介紹了ReentrantLock 互斥鎖,在同一時(shí)間只能被一個(gè)線程所占有,在被持有后并未釋放之前,其他線程若想獲得該鎖只能等待或放棄,需要的朋友可以參考下2017-05-05
Dubbo異步調(diào)用的實(shí)現(xiàn)介紹
dubbo默認(rèn)使用同步的方式調(diào)用。但在有些特殊的場景下,我們可能希望異步調(diào)用dubbo接口,從而避免不必要的等待時(shí)間,這時(shí)候我們就需要用到異步。那么dubbo的異步是如何實(shí)現(xiàn)的呢?下面就來看看這個(gè)問題2022-09-09

