java实现接口幂等_Spring Boot + Redis 实现接口幂等性

964129e8ae8ba3be519768eb31d47f95.png

Hi ! 我是小小,今天是本周的第四篇,第四篇主要内容是 Spring Boot + Redis 实现接口幂等性

介绍

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

数据库建立唯一索引

token机制

悲观锁或者是乐观锁

先查询后判断

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

347f2d97f46edfb97ef1fc221cae98ce.png

实现过程

引入 maven 依赖

org.springframework.boot

spring-boot-starter-data-redis

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;

/**

* @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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值