Springboot多实例启动定时任务
1.自备springboot项目
2.启动实例一,配置8080(默认的端口)
3.配置8081实例2, 指定启动的端口
4.定时任务
@Service @Slf4j public class ScheduleService { @Scheduled(cron = "0/10 * * * * ? ") public void sayHello(){ log.info("当前线程{},定时任务执行,{}", Thread.currentThread().getName(), "hello world"); } }
5.查看8080,可以看出8080的实例定时任务已执行
6.查看8081, 定时任务也执行
7.从结果看实例一和实例二都在执行定时任务,但是需要注意:如果定时任务在执行库存等操作,需要注意是否需要两个实例都执行还是只需要一个实例执行。
8.使用redis的分布式锁,抢到锁再执行,key的过期时间为30s
package com.frank.redis.util; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.time.Duration; import java.util.concurrent.TimeUnit; /** * @author 小石潭记 * @date 2021/6/8 21:13 * @Description: ${todo} */ @Component public class RedisLockUtil { @Autowired private StringRedisTemplate stringRedisTemplate; /** * Redis加锁的操作 * * @param key * @param value * @return */ public Boolean tryLock(String key, String value) { if (stringRedisTemplate.opsForValue().setIfAbsent(key, value)) { // 设置key 30s过期 stringRedisTemplate.expire(key, 30, TimeUnit.SECONDS); return true; } String currentValue = stringRedisTemplate.opsForValue().get(key); if (StringUtils.isNotEmpty(currentValue) && Long.valueOf(currentValue) < System.currentTimeMillis()) { //获取上一个锁的时间 如果高并发的情况可能会出现已经被修改的问题所以多一次判断保证线程的安全 String oldValue = stringRedisTemplate.opsForValue().getAndSet(key, value); if (StringUtils.isNotEmpty(oldValue) && oldValue.equals(currentValue)) { return true; } } return false; } /** * Redis解锁的操作 * * @param key * @param value */ public void unlock(String key, String value) { String currentValue = stringRedisTemplate.opsForValue().get(key); try { if (StringUtils.isNotEmpty(currentValue) && currentValue.equals(value)) { stringRedisTemplate.opsForValue().getOperations().delete(key); } } catch (Exception e) { } } }
9.定时任务修改
package com.frank.asynService.service; import com.frank.redis.util.RedisLockUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; /** * @author 小石潭记 * @date 2020/10/27 11:47 * @Description: ${todo} */ @Service @Slf4j public class ScheduleService { @Autowired private RedisLockUtil redisLock; @Scheduled(cron = "0/10 * * * * ? ") public void sayHello(){ String key = "dec_store_lock"; long time = System.currentTimeMillis(); try { //如果加锁失败 if (!redisLock.tryLock(key, String.valueOf(time))) { return; } // 执行真正的业务操作 log.info("当前线程{},定时任务执行,{}", Thread.currentThread().getName(), "hello world"); } catch (Exception e) { //解锁 异常 redisLock.unlock(key, String.valueOf(time)); return; } } }
10.查看定时任务执行,只有抢到锁之后才会执行,21.30.20时间段只有一个实例执行了定时任务
上一篇:
IDEA上Java项目控制台中文乱码