首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

分布式环境保证定时任务的幂等性

提供接口服务的API部署在了8台机器上,要保证定时任务只在一台机器上跑,因为有些定时任务不能同时进行,并且多台机器同时执行定时任务也浪费了资源,这就涉及到锁的问题。

方案一:根据机器的IP来限制

因为部署服务的8台机器ip是已知的,那么就通过ip来限制哪几台机器上的应用可以跑定时任务,获取本服务器ip方法,请移步这里

@Component

public class RegularTask {

@Lazy

@Scheduled(cron = "")

public void send() {

String ip = IPUtil.getLocalIP(); //获取本台服务器ip

String allowIp = PropertiesUtil.get("RUN_TASK_IP");//允许的跑定时任务的ip放在properties文件中或者配置在数据库中

if (allowIp.indexOf(ip) == -1) { //ip不匹配直接return

return;

}

//TODO do task

}

}

方案二:redis的分布式锁实现

让分布式应用去争取锁,谁抢到了谁执行。注意很多人会将redis.setInx(key,value)方法用于实现分布式锁,但是这个方法有漏洞,更多的关于redis分布式锁,请移步这里

@Component

public class RegularTask {

@Autowired

private JedisPool jedisPool;

@Lazy

@Scheduled(cron = "")

public void send() {

Jedis jedis =null;

try {

jedis = jedisPool.getResource();

boolean isLock = this.tryLock(jedis, "lock_ip_key", RandomStringUtils.randomNumeric(16), 1800); //过期时间为30min

if (isLock) {

//TODO do task

}

}catch (Exception e){

log.error("");

}finally {

if(jedis!=null){

jedis.close();

}

}

}

private static final String LOCKED_SUCCESS = "OK";

private static final String NX = "NX";

private static final String EXPIRE_TIME = "EX";

public static boolean tryLock(Jedis jedis, String lockKey, String uniqueId, long expireTime) {

String result = jedis.set(lockKey, uniqueId, NX, EXPIRE_TIME, expireTime);

return LOCKED_SUCCESS.equals(result);

}

}

方案三:zookeeper客户端curator

利用zookeeper来实现Master选举,只有Master机器(leader)上能执行定时任务。分布式机器同时在同一节点下创建子节点,而zookeeper保证了只有一个能创建成功,Curator里面就封装了这些操作。选举分为Leader Latch和Leader Election两种选举方案,这里使用Leader Latch实现。更多的关于zookeeper客户端curator,请移步这里

curator-recipes

2.4.1

@Component

public class RegularTask {

private static final Logger log = LoggerFactory.getLogger(RegularTask.class);

private static final String ZOOKEEPER_STR = "10.25.142.55:2181,10.48.24.36:2181";

private static CuratorFramework curatorFramework;

private static LeaderLatch leaderLatch;

static {

RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

curatorFramework = CuratorFrameworkFactory.newClient(ZOOKEEPER_STR, retryPolicy);

curatorFramework.start();

leaderLatch = new LeaderLatch(curatorFramework, "/regulartask");

try {

leaderLatch.start();

} catch (Exception e) {

log.error("LeaderLatch start error:{}", e);

}

}

@Lazy

@Scheduled(cron = "")

public void send() {

try {

if (!leaderLatch.hasLeadership()) {

log.info("current mechine is not a leader");

return;

}

//TODO 定时任务逻辑

} catch (Exception e) {

log.error("regulartask run error:{}", e);

} finally {

try {

if (leaderLatch != null) {

leaderLatch.close();

}

} catch (IOException e) {

log.error("leaderLatch close error:{}", e);

e.printStackTrace();

}

}

}

}

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180614G1483G00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券