Redis increment 函数处理并发序列号

1. 创建Spring Boot项目

首先,创建一个新的Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来生成项目结构。选择以下依赖:

  • Spring Web
  • Spring Data Redis
  • Lombok(可选,用于简化代码)

2. 配置application.yml

在你的 ​application.yml​文件中添加Redis配置:

spring:
  cache:
    type: GENERIC
  redis:
    host: ${sy.redis.ip}
    password:
    port: ${sy.redis.port}
    database: ${sy.redis.database}

3. 创建缓存配置类

创建一个配置类来手动配置基于Redis的缓存管理器:

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(10)) // 设置缓存过期时间
                .disableCachingNullValues()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(cacheConfiguration)
                .build();
    }
}

4. 创建服务类

创建一个服务类来使用Redis的 ​INCR​方法生成每天的序号

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Service
public class SequenceService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public long getDailySequence() {
        String dateStr = DateUtils.format(new Date(), "yyyy-MM-dd");
        String key = "dailySequence_" + dateStr;
        // 执行 increment 操作
        Long applicantNumber = redisTemplate.opsForValue().increment(key);
        // 设置过期时间为2天,不设置默认永久
        redisTemplate.expire(key, 2, TimeUnit.DAYS);
        //redisTemplate.expire(key) // 查询key的过期时间。
        //-1: 表示键存在但没有设置过期时间。
        //-2: 表示键不存在。
        //返回秒:如上面返回值是 172780,这意味着该键将在大约 172780 秒(约 48 小时)后过期。
        return applicantNumber;
    }
}

5. 创建控制器

创建一个控制器来暴露获取每天序号的API:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SequenceController {

    @Autowired
    private SequenceService sequenceService;

    @GetMapping("/daily-sequence")
    public String getDailySequence() {
        long sequence = sequenceService.getDailySequence();
        return "Daily sequence: " + sequence;
    }
}

6. 启动类

确保你的启动类包含 ​@EnableCaching​注解以启用缓存功能:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class RedisIncrApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedisIncrApplication.class, args);
    }
}

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中使用Redis实现乐观锁处理并发情况,可以通过使用Redis的命令来实现。 乐观锁是一种乐观思想,基于数据版本的控制来实现并发控制。在Redis中,可以使用WATCH命令来实现乐观锁的并发控制。 在业务代码中,可以首先使用WATCH命令监视需要控制并发的数据的版本号。然后在确认无并发情况后,使用MULTI命令开启事务,执行需要的操作,并在最后通过EXEC命令提交事务。 Redis在执行事务期间,如果被监视的数据的版本号发生了变化,那么会放弃执行事务,并返回nil给客户端。这样就能确保在事务执行期间,数据不会被其他客户端修改。 下面是一个示例代码: ``` @Autowired private RedisTemplate redisTemplate; public void optimisticLock(String key) { boolean success = false; while (!success) { redisTemplate.watch(key); // 监视key String value = (String) redisTemplate.opsForValue().get(key); // 进行业务逻辑判断 if (businessLogic(value)) { redisTemplate.multi(); // 开启事务 // 执行需要的操作 redisTemplate.opsForValue().set(key, newValue); List<Object> results = redisTemplate.exec(); // 提交事务 if (results != null) { success = true; // 事务执行成功 } } else { redisTemplate.unwatch(); // 放弃监视 break; } } } ``` 通过使用Redis的WATCH命令和事务操作,可以实现乐观锁的并发控制,确保在执行事务期间数据不会被其他客户端修改,从而解决并发问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值