Spring-Cloud-Oauth2-Swagger的feign微服务间调用

Spring-Cloud-Oauth2-Swagger项目feign微服务调用其它服务失败,Postan测试提示401错误"invalid_token":

Swagger-UI测试提示500“内部服务器错误”:

控制台提示“hystrixy异常“错误:

[Request processing failed; nested exception is com.netflix.hystrix.exception.HystrixRuntimeException]

关掉feign的hystrix功能,微服务间调用可以正常进行:feign.hystrix.enabled=false

采用feign就是要运用其内含的hystrix功能,不能关闭。

查阅资料说明:feign-hystrix默认采用的是thread隔离策略,可以改为信号semaphore隔离:

hystrix.command.default.execution.isolation.strategy=SEMAPHORE

由于采用了spring boot版本2.2.4,不允许这样设置,而且诸多资料说明:即使可以这样设置,feign-hystrix就没有意义了。

于是决定自定义并发策略,将现有的并发策略作为新并发策略的成员变量; 在新并发策略中,返回现有并发策略的线程池、Queue,定义的组件类如下:

@Component
public class SpcFcs extends HystrixConcurrencyStrategy {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(SpcFcs.class);
    private HystrixConcurrencyStrategy delegate;
 
    public SpcFcs() {
        try {
            this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy();
            if (this.delegate instanceof SpcFcs) {
                // Welcome to singleton hell...
                return;
            }
            HystrixCommandExecutionHook commandExecutionHook =
                    HystrixPlugins.getInstance().getCommandExecutionHook();
            HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
            HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
            HystrixPropertiesStrategy propertiesStrategy =
                    HystrixPlugins.getInstance().getPropertiesStrategy();
            this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, propertiesStrategy);
            HystrixPlugins.reset();
            HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
            HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
            HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
            HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
            HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
        } catch (Exception e) {
            LOGGER.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);
        }
    }
 
    private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,
                                                 HystrixMetricsPublisher metricsPublisher, HystrixPropertiesStrategy propertiesStrategy) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Current Hystrix plugins configuration is [" + "concurrencyStrategy ["
                    + this.delegate + "]," + "eventNotifier [" + eventNotifier + "]," + "metricPublisher ["
                    + metricsPublisher + "]," + "propertiesStrategy [" + propertiesStrategy + "]," + "]");
            LOGGER.debug("Registering Sleuth Hystrix Concurrency Strategy.");
        }
    }
 
    @Override
    public <T> Callable<T> wrapCallable(Callable<T> callable) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return new WrappedCallable<>(callable, requestAttributes);
    }
 
    @Override
    public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
                                            HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize,
                                            HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime,
                unit, workQueue);
    }
 
    @Override
    public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
                                            HystrixThreadPoolProperties threadPoolProperties) {
        return this.delegate.getThreadPool(threadPoolKey, threadPoolProperties);
    }
 
    @Override
    public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
        return this.delegate.getBlockingQueue(maxQueueSize);
    }
 
    @Override
    public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) {
        return this.delegate.getRequestVariable(rv);
    }
 
    static class WrappedCallable<T> implements Callable<T> {
        private final Callable<T> target;
        private final RequestAttributes requestAttributes;
 
        public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) {
            this.target = target;
            this.requestAttributes = requestAttributes;
        }
 
        @Override
        public T call() throws Exception {
            try {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                return target.call();
            } finally {
                RequestContextHolder.resetRequestAttributes();
            }
        }
    }
}
再将这个策略类作为bean配置到feign的配置类FeignConfiguration

中:

@Configuration
public class FeignCfg {
    @Value("${security.oauth2.client.user-authorization-uri}")
    private String authorizeUrl;

    @Value("${security.oauth2.client.access-token-uri}")
    private String tokenUrl;

    @Value("${security.oauth2.client.client-id}")
    private String clientId;

    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor
        (@Qualifier("oauth2ClientContext") OAuth2ClientContext oauth2ClientContext) {
        return new OAuth2FeignRequestInterceptor(oauth2ClientContext, resource());
    }

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
        resource.setAccessTokenUri(tokenUrl);
        resource.setUserAuthorizationUri(authorizeUrl);
        resource.setClientId(clientId);
        return resource;
    }
    
    @Bean
    public SpcFcs feignHystrixConcurrencyStrategy() {
      return new SpcFcs();
    }    
}
重新测试,Postman正常:

注释掉feign的配置类FeignConfiguration添加的这个策略类bean,Postman也可以正常实现feign服务再调用其它服务,说明系统可以自动引用这个自定义策略组件。

Swagger-ui测试仍然显示:

可能是Swagger调用不能在feign服务间传递token,目前还没有找到合适的方法纠正这个缺陷。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值