iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot结合Redis实现接口幂等性的示例代码
  • 397
分享到

SpringBoot结合Redis实现接口幂等性的示例代码

2024-04-02 19:04:59 397人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录介绍实现过程引入 Maven 依赖spring 配置文件写入引入 Redis自定义注解token 的创建和实现拦截器的配置测试用例介绍 幂等性的概念是,任意多次执行所产生的影响都

介绍

幂等性的概念是,任意多次执行所产生的影响都与一次执行产生的影响相同,按照这个含义,最终的解释是对数据库的影响只能是一次性的,不能重复处理。手段如下

小小主要带你们介绍Redis实现自动幂等性。其原理如下图所示。

实现过程

引入 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 #本机的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相关的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;
 

@Component
public class RedisUtil {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    
    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;
    }
 
    
    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;
    }
 
    
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
 
    
    public boolean remove(final String key) {
        if (exists(key)) {
            Boolean delete = redisTemplate.delete(key);
            return delete;
        }
        return false;
 
    }
 
    
    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;
    }
 
 
}

自定义注解

自定义一个注解,定义此注解的目的是把它添加到需要实现幂等的方法上,只要某个方法注解了其,都会自动实现幂等操作。其代码如下

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIdempotent {
  
}

token 的创建和实现

token 服务接口,我们新建一个接口,创建token服务,里面主要是有两个方法,一个用来创建 token,一个用来验证token

public interface TokenService {
 
    
    public  String createToken();
 
    
    public boolean checkToken(httpservletRequest request) throws Exception;
 
}

token 的实现类,token中引用了服务的实现类,token引用了 redis 服务,创建token采用随机算法工具类生成随机 uuid 字符串,然后放入 redis 中,如果放入成功,返回token,校验方法就是从 header 中获取 token 的值,如果不存在,直接跑出异常,这个异常信息可以被直接拦截到,返回给前端

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;
 

@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private RedisUtil redisService;
 
    
    @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;
    }
 
    
    @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();
    }
 
    
    @Override
    public void addInterceptors(InterceptorReGIStry registry) {
        registry.addInterceptor(authInterceptor());
//                .addPathPatterns("/ksb
@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) ;
    }
}

用浏览器进行访问

用获取到的token第一次访问

用获取到的token再次访问

可以看到,第二次访问失败,即,幂等性验证通过。

到此这篇关于SpringBoot结合Redis实现接口幂等性的示例代码的文章就介绍到这了,更多相关SpringBoot Redis接口幂等性内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot结合Redis实现接口幂等性的示例代码

本文链接: https://www.lsjlt.com/news/152375.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作