Springboot多实例启动定时任务

Springboot多实例启动定时任务

2023年7月21日发(作者:)

Springboot多实例启动定时任务1.⾃备springboot项⽬2.启动实例⼀,配置8080(默认的端⼝)3.配置8081实例2, 指定启动的端⼝4.定时任务@Service@Slf4jpublic class ScheduleService { @Scheduled(cron = "0/10 * * * * ? ") public void sayHello(){ ("当前线程{},定时任务执⾏,{}", tThread().getName(), "hello world"); }}5.查看8080,可以看出8080的实例定时任务已执⾏6.查看8081, 定时任务也执⾏7.从结果看实例⼀和实例⼆都在执⾏定时任务,但是需要注意:如果定时任务在执⾏库存等操作,需要注意是否需要两个实例都执⾏还是只需要⼀个实例执⾏。 8.使⽤redis的分布式锁,抢到锁再执⾏,key的过期时间为30spackage ;import Utils;import red;import RedisTemplate;import ent;import on;import it;/** * @author ⼩⽯潭记 * @date 2021/6/8 21:13 * @Description: ${todo} */@Componentpublic class RedisLockUtil { @Autowired private StringRedisTemplate stringRedisTemplate; /** * Redis加锁的操作 * * @param key * @param value * @return */ public Boolean tryLock(String key, String value) { if (Value().setIfAbsent(key, value)) { // 设置key 30s过期 (key, 30, S); return true; } String currentValue = Value().get(key); if (mpty(currentValue) && f(currentValue) < tTimeMillis()) { //获取上⼀个锁的时间 如果⾼并发的情况可能会出现已经被修改的问题所以多⼀次判断保证线程的安全 String oldValue = Value().getAndSet(key, value); if (mpty(oldValue) && (currentValue)) { return true; } } return false; } /** * Redis解锁的操作 * * @param key * @param value */ public void unlock(String key, String value) { String currentValue = Value().get(key); try { if (mpty(currentValue) && (value)) { Value().getOperations().delete(key); } } catch (Exception e) { } }}9.定时任务修改package e;import ockUtil;import 4j;import red;import led;import e;/** * @author ⼩⽯潭记 * @date 2020/10/27 11:47 * @Description: ${todo} */@Service@Slf4jpublic class ScheduleService { @Autowired private RedisLockUtil redisLock; @Scheduled(cron = "0/10 * * * * ? ") public void sayHello(){ String key = "dec_store_lock"; long time = tTimeMillis(); try { //如果加锁失败 if (!k(key, f(time))) { return; } // 执⾏真正的业务操作 ("当前线程{},定时任务执⾏,{}", tThread().getName(), "hello world"); } catch (Exception e) { //解锁 异常 (key, f(time)); return; } }}10.查看定时任务执⾏,只有抢到锁之后才会执⾏,21.30.20时间段只有⼀个实例执⾏了定时任务

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1689929920a295204.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信