SpringBootが実践する---クラスタ環境におけるRedisによるタイミングタスクの実現

12616 ワード

私たちは今マイクロサービスが流行していることを知っていて、そのため、多くの中小企業は自分の以前のフレームワークを改造して、その中でSpringCloudが最も多いことを知っていますが、SpringCloudはタイミングタスクを加えると、1台のサーバーでよくサポートされていますが、クラスタサービス(複数のサービスに関連すると)は分布式ロックを使います.最も簡単な案はRedisを使うことです.
ステップ1:プロファイルアプリケーション.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=

ステップ2:jarパケット依存性を追加します.ここではmavenを例にpom.xmlに追加
		
			org.springframework.boot
			spring-boot-starter-data-redis
		

第三部:redisツール類の書き方
1):新規ロック.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 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());
        }
    }

}

ステップ4:タイミングタスクを追加します.ここでは1秒に1回実行します.@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);
        }

    }
}

ステップ5:アプリケーション起動クラスに注記@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);
   }
}

ステップ6では、2つの異なるポートで2つのSpringbootサービスを開始します.
通常、同じ時間に1つのサービスしか実行されないタイミングタスクが実行中!! 
説明ですが、複数のサービスのタイミングタスクの実行が速い場合や、2つのサービスの起動時間が非常に近い場合、ロック判定が不正確な場合があり、両方のサービスのタイミングタスクが同時に実行されます!
機能完備
だから3歩目の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 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

説明は同時に1つのサーバーのタイミングタスクだけが実行中で、そのサーバーは先にredisのロックを奪って、それは実行します!!