我们知道现在微服务很流行,为此,许多中小型企业都将自己以前的框架加以改造,其中以SpringCloud为最多,但是SpringCloud如果要加定时任务的话,在单台服务器上很好支持,但是涉及到集群服务(多台服务的话)就要用到分布式锁了,最简单的方案是用Redis,好了废话不多说,直接上代码.

第一步:在配置文件application.properties中加入Redis的相关配置:

#Redis配置
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=

第二步:添加jar包依赖,这里以maven为例,pom.xml中加入

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

第三部:redis工具类的写法

1):新建Lock.java实体类

package com.great.springboot2.distributed;

/**
 * 全局锁,包括锁的名称 Created by zuoguobin on 2017/4/1.
 */
public class Lock {
    private String name;
    private String value;

    public Lock(String name, String value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }
}

2):新建DistributedLockHandler.java分布式锁工具类,此时注意:@Component的写法,目的是为了注入值

package com.great.springboot2.distributed;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * Created by zuoguobin on 2017/4/1.
 */
@Component
public class DistributedLockHandler {

    private static final Logger logger = LoggerFactory.getLogger(DistributedLockHandler.class);
    private final static long LOCK_EXPIRE = 30 * 1000L;// 单个业务持有锁的时间30s,防止死锁
    private final static long LOCK_TRY_INTERVAL = 30L;// 默认30ms尝试一次
    private final static long LOCK_TRY_TIMEOUT = 20 * 1000L;// 默认尝试20s

    @Autowired
    private StringRedisTemplate template;

    /**
     * 尝试获取全局锁
     *
     * @param lock
     *            锁的名称
     * @return true 获取成功,false获取失败
     */
    public boolean tryLock(Lock lock) {
        return getLock(lock, LOCK_TRY_TIMEOUT, LOCK_TRY_INTERVAL, LOCK_EXPIRE);
    }

    /**
     * 尝试获取全局锁
     *
     * @param lock
     *            锁的名称
     * @param timeout
     *            获取超时时间 单位ms
     * @return true 获取成功,false获取失败
     */
    public boolean tryLock(Lock lock, long timeout) {
        return getLock(lock, timeout, LOCK_TRY_INTERVAL, LOCK_EXPIRE);
    }

    /**
     * 尝试获取全局锁
     *
     * @param lock
     *            锁的名称
     * @param timeout
     *            获取锁的超时时间
     * @param tryInterval
     *            多少毫秒尝试获取一次
     * @return true 获取成功,false获取失败
     */
    public boolean tryLock(Lock lock, long timeout, long tryInterval) {
        return getLock(lock, timeout, tryInterval, LOCK_EXPIRE);
    }

    /**
     * 尝试获取全局锁
     *
     * @param lock
     *            锁的名称
     * @param timeout
     *            获取锁的超时时间
     * @param tryInterval
     *            多少毫秒尝试获取一次
     * @param lockExpireTime
     *            锁的过期
     * @return true 获取成功,false获取失败
     */
    public boolean tryLock(Lock lock, long timeout, long tryInterval, long lockExpireTime) {
        return getLock(lock, timeout, tryInterval, lockExpireTime);
    }

    /**
     * 操作redis获取全局锁
     *
     * @param lock
     *            锁的名称
     * @param timeout
     *            获取的超时时间
     * @param tryInterval
     *            多少ms尝试一次
     * @param lockExpireTime
     *            获取成功后锁的过期时间
     * @return true 获取成功,false获取失败
     */
    public boolean getLock(Lock lock, long timeout, long tryInterval, long lockExpireTime) {
        try {
            if (StringUtils.isEmpty(lock.getName()) || StringUtils.isEmpty(lock.getValue())) {
                return false;
            }
            long startTime = System.currentTimeMillis();
            do {
                if (!template.hasKey(lock.getName())) {
                    ValueOperations<String, String> ops = template.opsForValue();
                    ops.set(lock.getName(), lock.getValue(), lockExpireTime, TimeUnit.MILLISECONDS);
                    return true;
                } else {// 存在锁
                    logger.debug("lock is exist!!!");
                }
                if (System.currentTimeMillis() - startTime > timeout) {// 尝试超过了设定值之后直接跳出循环
                    return false;
                }
                Thread.sleep(tryInterval);
            } while (template.hasKey(lock.getName()));
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
            return false;
        }
        return false;
    }

    /**
     * 释放锁
     */
    public void releaseLock(Lock lock) {
        if (!StringUtils.isEmpty(lock.getName())) {
            template.delete(lock.getName());
        }
    }

}

第四步:添加定时任务,这里是一秒执行一次,注意@Component要加上让系统扫描到,停用定时任务就把它拿掉!

package com.great.springboot2.distributed;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

@Component
public class MyScheduler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    DistributedLockHandler distributedLockHandler;

    @Scheduled(fixedRate = 6000)
    public void task() throws InterruptedException {

        Lock lock=new Lock("testlock","lockvalue");
        if(distributedLockHandler.tryLock(lock)){
            //Thread.sleep(40000);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            logger.info("everOne22222 start....。。。。。。。。。。。startTime="+ df.format(System.currentTimeMillis()));
            System.out.println("template   --"+template);
            System.out.println("distributedLockHandler   --"+distributedLockHandler);
            try{
                Thread.sleep(10000);
            }catch (Exception e){

            }

            //statusTask.healthCheck();
            // int i=10/0;
            logger.info("everOne222222 end...。。。。。。。。。。。。 endTime="+df.format(System.currentTimeMillis()));
            distributedLockHandler.releaseLock(lock);
        }

    }
}

第五步:在应用程序启动类加上注解@EnableScheduling,这个是要加上的,对计划任务的支持

package com.great.springboot2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
public class Springboot2Application {

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

第六步,分别用两个不同的端口启动两个Springboot服务

正常情况下,同一时间只有一个服务的定时任务在运行中!! 

说明,但是当多个服务的定时任务执行很快或者2个服务的启动时间非常接近的时候,会存在锁判断不准确的情况,两个服务中的定时任务同时都在运行!

功能完善

因此对第三步的DistributedLockHandler.java分布式锁工具类做了一点修改:

package com.great.springboot2.distributed;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * Created by zuoguobin on 2017/4/1.
 */
@Component
public class DistributedLockHandler {

    private static final Logger logger = LoggerFactory.getLogger(DistributedLockHandler.class);
    private final static long LOCK_EXPIRE = 30 * 1000L;// 单个业务持有锁的时间30s,防止死锁

    @Autowired
    private StringRedisTemplate template;

    /**
     * 尝试获取全局锁
     *
     * @param lock
     *            锁的名称
     * @return true 获取成功,false获取失败
     */
    public boolean tryLock(Lock lock) {
        return getLock(lock, LOCK_EXPIRE);
    }
    
    

    /**
     * 尝试获取全局锁
     *
     * @param lock
     *            锁的名称
     * @param lockExpireTime
     *            锁的过期
     * @return true 获取成功,false获取失败
     */
    public boolean tryLock(Lock lock, long lockExpireTime) {
        return getLock(lock, lockExpireTime);
    }

    /**
     * 操作redis获取全局锁
     *
     * @param lock
     *            锁的名称
     * @param lockExpireTime
     *            获取成功后锁的过期时间
     * @return true 获取成功,false获取失败
     */
    public boolean getLock(Lock lock, long lockExpireTime) {
        try {
            if (StringUtils.isEmpty(lock.getName()) || StringUtils.isEmpty(lock.getValue())) {
                return false;
            }
            long startTime = System.currentTimeMillis();

                if (!template.hasKey(lock.getName())) {
                    ValueOperations<String, String> ops = template.opsForValue();
                    ops.set(lock.getName(), lock.getValue(), lockExpireTime, TimeUnit.MILLISECONDS);
                    return true;
                } else {// 存在锁
                    logger.error("lock is exist!!!");
                    return false;
                }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
    }

    /**
     * 释放锁
     */
    public void releaseLock(Lock lock) {
        if (!StringUtils.isEmpty(lock.getName())) {
            template.delete(lock.getName());
        }
    }

}

最终的执行结果:

A服务器日志:

2018-07-18 15:05:40.299  INFO 93616 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne22222 start....。。。。。。。。。。。startTime=2018-07-18 15:05:40
2018-07-18 15:06:11.301  INFO 93616 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne222222 end...。。。。。。。。。。。。 endTime=2018-07-18 15:06:11
2018-07-18 15:06:40.301  INFO 93616 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne22222 start....。。。。。。。。。。。startTime=2018-07-18 15:06:40
2018-07-18 15:07:11.318  INFO 93616 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne222222 end...。。。。。。。。。。。。 endTime=2018-07-18 15:07:11
2018-07-18 15:07:40.299  INFO 93616 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne22222 start....。。。。。。。。。。。startTime=2018-07-18 15:07:40
2018-07-18 15:08:11.331  INFO 93616 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne222222 end...。。。。。。。。。。。。 endTime=2018-07-18 15:08:11
2018-07-18 15:08:40.335 ERROR 93616 --- [pool-1-thread-1] c.g.s.d.DistributedLockHandler           : lock is exist!!!
2018-07-18 15:09:40.299 ERROR 93616 --- [pool-1-thread-1] c.g.s.d.DistributedLockHandler           : lock is exist!!!
2018-07-18 15:10:40.314 ERROR 93616 --- [pool-1-thread-1] c.g.s.d.DistributedLockHandler           : lock is exist!!!

B服务器日志:

2018-07-18 15:08:11.602  INFO 90116 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne22222 start....。。。。。。。。。。。startTime=2018-07-18 15:08:11
2018-07-18 15:08:42.604  INFO 90116 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne222222 end...。。。。。。。。。。。。 endTime=2018-07-18 15:08:42
2018-07-18 15:09:11.000  INFO 90116 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne22222 start....。。。。。。。。。。。startTime=2018-07-18 15:09:11
2018-07-18 15:09:42.002  INFO 90116 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne222222 end...。。。。。。。。。。。。 endTime=2018-07-18 15:09:42
2018-07-18 15:10:11.001  INFO 90116 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne22222 start....。。。。。。。。。。。startTime=2018-07-18 15:10:11
2018-07-18 15:10:42.003  INFO 90116 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne222222 end...。。。。。。。。。。。。 endTime=2018-07-18 15:10:42
2018-07-18 15:11:11.000  INFO 90116 --- [pool-1-thread-1] c.g.springboot2.distributed.MyScheduler  : everOne22222 start....。。。。。。。。。。。startTime=2018-07-18 15:11:11

说明同时只有一个服务器的定时任务在执行中,那个服务器先抢到redis的锁,那个就去执行!!

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐