All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.echo.sharding.algorithm.HistoryRangeShardingAlgorithm Maven / Gradle / Ivy

The newest version!
package cn.echo.sharding.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 按历史备份拆表
 * @author lonyee
 *
 */
public class HistoryRangeShardingAlgorithm implements RangeShardingAlgorithm {

    @Override
    public Collection doSharding(Collection collection, RangeShardingValue rangeShardingValue) {
        Set collect = new HashSet<>();
        Range valueRange = rangeShardingValue.getValueRange();
        Date startTime = valueRange.lowerEndpoint();
        Date endTime = valueRange.upperEndpoint();
        
        Calendar calendar = Calendar.getInstance();
        LocalDateTime currDate = LocalDateTime.now();

        while (startTime.getTime()<=endTime.getTime()){
            LocalDateTime shardingDate = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault());
            long interval = ChronoUnit.MONTHS.between(currDate, shardingDate);
            for (String each : collection) {
            	//2个月前查记录表,2个月内查原表
    			if (interval>=2L) {
    	            if (each.endsWith("history")) {
                        collect.add(each);
    	            }
    			} else {
    				if (!each.endsWith("history")) {
                        collect.add(each);
    				}
                }
            	//当前表和历史表都加入了就没必须循环了
                if (collect.size()>=2) {
                    return collect;
                }
            }
            calendar.setTime(startTime);
            calendar.add(Calendar.DATE, 1);
            startTime = calendar.getTime();
        }
        return collect;
    }
    
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy