id本地缓存策略

110 篇文章 4 订阅

思路是每次去生成id都要去获取比较慢,可以在启动的时候先获取部分id到缓存中,然后直接在缓存里获取id,当id数量下降到一定程度的时候再去补充id到缓存中

上配置类

package com.felix.spring_cloud_one.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(
        prefix = "idsetting"
)
public class IdGenerateProperties {

    private IdGenerateProperties.IdentTooker identTooker = new IdGenerateProperties.IdentTooker();

    public void setIdentTooker(IdentTooker identTooker) {
        this.identTooker = identTooker;
    }

    public IdentTooker getIdentTooker() {
        return identTooker;
    }

    public static class IdentTooker {
        private String enable = "false";
        private Integer limitAllowExistNumber = 30;
        private Integer maxKeepNumber = 200;
        private Integer perRequestStep = 100;

        public IdentTooker() {
        }

        public String getEnable() {
            return this.enable;
        }

        public void setEnable(String enable) {
            this.enable = enable;
        }

        public Integer getLimitAllowExistNumber() {
            return this.limitAllowExistNumber;
        }

        public void setLimitAllowExistNumber(Integer limitAllowExistNumber) {
            this.limitAllowExistNumber = limitAllowExistNumber;
        }

        public Integer getMaxKeepNumber() {
            return this.maxKeepNumber;
        }

        public void setMaxKeepNumber(Integer maxKeepNumber) {
            this.maxKeepNumber = maxKeepNumber;
        }

        public Integer getPerRequestStep() {
            return this.perRequestStep;
        }

        public void setPerRequestStep(Integer perRequestStep) {
            this.perRequestStep = perRequestStep;
        }
    }


}

id获取及补充类

package com.felix.spring_cloud_one.util;

import com.felix.spring_cloud_one.config.ClientResult;
import com.felix.spring_cloud_one.config.IdGenerateProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class IdTook {

    private static final Logger log = LoggerFactory.getLogger(IdTook.class);
    private static IdGenerateProperties idGenerateProperties;
    private static IdentGenerateClient identGenerateClient;
    private static final LinkedBlockingQueue<Long> IDENT_POOL = new LinkedBlockingQueue<>();
    //private static final LinkedBlockingQueue<Boolean> IDENT_POOL_LISTEN = new LinkedBlockingQueue<>();
    private static final ExecutorService SINGLE_THREAD_EXECUTOR;
    private static IdTook.ListenRunnable listenRunnable;


    static {
        SINGLE_THREAD_EXECUTOR = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), (r) -> {
            return new Thread(r, "id-took-thread");
        }, new ThreadPoolExecutor.DiscardOldestPolicy());
        listenRunnable = new IdTook.ListenRunnable();
    }

    public IdTook() {
    }

    @Autowired
    public void setIdentFeignClient(IdentGenerateClient identGenerateClient) {
        //从id生成服务获取id
        IdTook.identGenerateClient = identGenerateClient;
    }

    @Autowired
    public void setDrawerProperties(IdGenerateProperties idGenerateProperties) {
        IdTook.idGenerateProperties = idGenerateProperties;
    }

    @PostConstruct
    public void initIdentPool() {
        SINGLE_THREAD_EXECUTOR.execute(listenRunnable);
    }

    public static Long take() {
        log.info("当前取号池剩余:{}个号码", IDENT_POOL.size());

        try {
            if (0 == IDENT_POOL.size()) {
                log.warn("取号线程异常中断,当前系统直接从生成器获取id");
                ClientResult<Long> clientResult = identGenerateClient.make();
                if (1 == clientResult.getCode()) {
                    return (Long)clientResult.getData();
                }
            }

            Long id = (Long)IDENT_POOL.poll(10L, TimeUnit.SECONDS);
            if (IDENT_POOL.size() < idGenerateProperties.getIdentTooker().getLimitAllowExistNumber()) {
                synchronized(listenRunnable) {
                    listenRunnable.notify();
                }
            }

            return id;
        } catch (InterruptedException var4) {
            log.error(var4.getMessage(), var4);
            throw new RuntimeException("取号超时,请确保已启用id取号器功能");
        }
    }

    private static void offer(Long... ids) {
        Long[] var1 = ids;
        int var2 = ids.length;

        for(int var3 = 0; var3 < var2; ++var3) {
            Long id = var1[var3];

            try {
                IDENT_POOL.offer(id, 1L, TimeUnit.SECONDS);
            } catch (InterruptedException var6) {
                log.warn("插入新号码失败");
            }
        }

    }

    private static class ListenRunnable implements Runnable {
        private ListenRunnable() {
        }

        public void run() {
            while(true) {
                synchronized(IdTook.listenRunnable) {
                    if (IdTook.IDENT_POOL.size() > IdTook.idGenerateProperties.getIdentTooker().getLimitAllowExistNumber()) {
                        try {
                            IdTook.listenRunnable.wait();
                        } catch (InterruptedException var8) {
                            var8.printStackTrace();
                        }
                    } else {
                        IdTook.log.info("取号池号码过少,获取新号码");
                        Integer step = IdTook.idGenerateProperties.getIdentTooker().getPerRequestStep();
                        step = step > 100 ? 100 : step;
                        int count = (int)Math.ceil((double)(IdTook.idGenerateProperties.getIdentTooker().getMaxKeepNumber() / step));
                        count = 0 == count ? 1 : count;

                        for(int i = 0; i < count; ++i) {
                            ClientResult<Long []> clientResult = IdTook.identGenerateClient.make(step);
                            if (1 == clientResult.getCode()) {
                                Long[] data = clientResult.getData();
                                IdTook.offer(data);
                            }
                        }
                    }
                }
            }
        }
    }


}

yml配置文件

idsetting:
  identTooker:
    limitAllowExistNumber: 5
    maxKeepNumber: 5
    perRequestStep: 5
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值