1. 程式人生 > 其它 >Soul原始碼分析 —— 好程式碼的味道

Soul原始碼分析 —— 好程式碼的味道

技術標籤:原始碼分析javaspring設計模式

Soul原始碼分析 —— 好程式碼的味道

對bean的操作

更靈活的生成bean和排序

@ConditionalOnProperty(name = "soul.cross.enabled", havingValue = "true")

@Order(-100)

@ConditionalOnMissingBean(value = SoulResult.class, search = SearchStrategy.ALL)

@ConditionalOnClass
(AlibabaDubboPlugin.class)

用Util類獲取bean

    @Bean
    public ApplicationContextAware applicationContextAware() {
        return new SoulApplicationContextAware();
    }

    /**
     * The type Soul application context aware.
     */
    public static class SoulApplicationContextAware implements ApplicationContextAware {
@Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { SpringBeanUtils.getInstance().setCfgContext((ConfigurableApplicationContext) applicationContext); } }
public final class SpringBeanUtils
{ private static final SpringBeanUtils INSTANCE = new SpringBeanUtils(); private ConfigurableApplicationContext cfgContext; private SpringBeanUtils() { } public static SpringBeanUtils getInstance() { return INSTANCE; } public <T> T getBean(final Class<T> type) { return cfgContext.getBean(type); } public void setCfgContext(final ConfigurableApplicationContext cfgContext) { this.cfgContext = cfgContext; } }

設計模式的使用

單例懶漢模式

public final class MetricsTrackerHandler {
	public static MetricsTrackerHandler getInstance() {
		return MetricsTrackerHandlerHolder.INSTANCE;
	}
	    
	private static class MetricsTrackerHandlerHolder {
		private static final MetricsTrackerHandler INSTANCE = new MetricsTrackerHandler();
	}
}

模版模式

public abstract class AbstractSoulPlugin implements SoulPlugin {

    protected abstract Mono<Void> doExecute(ServerWebExchange exchange, SoulPluginChain chain, SelectorData selector, RuleData rule);

    @Override
    public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
      ///code omitted
    }

執行緒池的拒絕策略

當所有執行緒都在工作並且佇列已滿,常見的策略有 (Reject, Caller-Runs, Discard, Discard-Oldest), 這裡看到新思路,就是阻塞caller thread.

private static class CallerWaitPolicy implements RejectedExecutionHandler {
    
        @Override
        public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
            try {
                log.warn("queue is full, trigger caller thread : {} wait", Thread.currentThread().getName());
                executor.getQueue().put(r);
            } catch (InterruptedException ex) {
                log.error("InterruptedException, discard {}", r);
            }
        }
    }

小結

未完,再開一篇