介绍
幂等性的概念是,任意多次执行所产生的影响都与一次执行产生的影响相同,按照这个含义,最终的解释是对数据库的影响只能是一次性的,不能重复处理。手段如下
- 数据库建立唯一索引
- 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;
/**
* @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();