当前位置: 首页 > news >正文

spring cloud Dalston.SR4 feign 实际开发中踩坑(二)

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

本文采用的springcloud 版本 Dalston.SR4   所有例子以Dalston.SR4 版本为准

spring cloud Dalston.SR4 feign 实际开发中踩坑(一)

https://my.oschina.net/u/2948566/blog/1591028

坑4、       无法扫描到引用包的feign接口

在实际的生产中 我们服务模块是有很多的, 如果 A的接口 B要调用 我们声明一次feigin客户端 api    然后C也要调A的接口  我们还要声明一次feigin客户端api   如果还有更多  就会有很多重复代码  为了提高代码复用,我们往往单独声明一个包来引入feigin 的api  其他包如果调用的化引入到工程中就行了   但是 问题来了 引用包无法被直接扫描到  我们知道 一个微服务模块 如果需要开启feign调用功能 需要加上

@EnableFeignClients 

源码:

/*
 * Copyright 2013-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.netflix.feign;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Import;

/**
 * Scans for interfaces that declare they are feign clients (via {@link FeignClient
 * <code>@FeignClient</code>}). Configures component scanning directives for use with
 * {@link org.springframework.context.annotation.Configuration
 * <code>@Configuration</code>} classes.
 *
 * @author Spencer Gibb
 * @author Dave Syer
 * @since 1.0
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(FeignClientsRegistrar.class)
public @interface EnableFeignClients {

	/**
	 * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation
	 * declarations e.g.: {@code @ComponentScan("org.my.pkg")} instead of
	 * {@code @ComponentScan(basePackages="org.my.pkg")}.
	 * @return the array of 'basePackages'.
	 */
	String[] value() default {};

	/**
	 * Base packages to scan for annotated components.
	 * <p>
	 * {@link #value()} is an alias for (and mutually exclusive with) this attribute.
	 * <p>
	 * Use {@link #basePackageClasses()} for a type-safe alternative to String-based
	 * package names.
	 *
	 * @return the array of 'basePackages'.
	 */
	String[] basePackages() default {};

	/**
	 * Type-safe alternative to {@link #basePackages()} for specifying the packages to
	 * scan for annotated components. The package of each class specified will be scanned.
	 * <p>
	 * Consider creating a special no-op marker class or interface in each package that
	 * serves no purpose other than being referenced by this attribute.
	 *
	 * @return the array of 'basePackageClasses'.
	 */
	Class<?>[] basePackageClasses() default {};

	/**
	 * A custom <code>@Configuration</code> for all feign clients. Can contain override
	 * <code>@Bean</code> definition for the pieces that make up the client, for instance
	 * {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}.
	 *
	 * @see FeignClientsConfiguration for the defaults
	 */
	Class<?>[] defaultConfiguration() default {};

	/**
	 * List of classes annotated with @FeignClient. If not empty, disables classpath scanning.
	 * @return
	 */
	Class<?>[] clients() default {};
}

     其中basePackages  声明 扫描  feignclient 注解所在的包的包路径  声明后就能扫描到你在该包下@FeignClient 标记的 feign接口

坑5、  无法扫描到引入包的服务降级实现,大多数情况 我们要对feignClient接口  显式声明一个fallback 以便进行服务降级   但是如果你的feignclient 接口 不在 springboot 的启动类的子类  会无法启动 显示

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean 
with name 'com.xxx.feign.api.UserService': 
FactoryBean threw exception on object creation; 
nested exception is java.lang.IllegalStateException:
 No fallback instance of type class com.xxx.feign.api.UserServiceHystrix found for feign client MEMBER-SERVICE

也就是你feign 接口的实现类  无法被注入

 

先看一下 源码:

/*
 * Copyright 2013-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.netflix.feign;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;

/**
 * Annotation for interfaces declaring that a REST client with that interface should be
 * created (e.g. for autowiring into another component). If ribbon is available it will be
 * used to load balance the backend requests, and the load balancer can be configured
 * using a <code>@RibbonClient</code> with the same name (i.e. value) as the feign client.
 *
 * @author Spencer Gibb
 * @author Venil Noronha
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FeignClient {

	/**
	 * The name of the service with optional protocol prefix. Synonym for {@link #name()
	 * name}. A name must be specified for all clients, whether or not a url is provided.
	 * Can be specified as property key, eg: ${propertyKey}.
	 */
	@AliasFor("name")
	String value() default "";

	/**
	 * The service id with optional protocol prefix. Synonym for {@link #value() value}.
	 *
	 * @deprecated use {@link #name() name} instead
	 */
	@Deprecated
	String serviceId() default "";

	/**
	 * The service id with optional protocol prefix. Synonym for {@link #value() value}.
	 */
	@AliasFor("value")
	String name() default "";
	
	/**
	 * Sets the <code>@Qualifier</code> value for the feign client.
	 */
	String qualifier() default "";

	/**
	 * An absolute URL or resolvable hostname (the protocol is optional).
	 */
	String url() default "";

	/**
	 * Whether 404s should be decoded instead of throwing FeignExceptions
	 */
	boolean decode404() default false;

	/**
	 * A custom <code>@Configuration</code> for the feign client. Can contain override
	 * <code>@Bean</code> definition for the pieces that make up the client, for instance
	 * {@link feign.codec.Decoder}, {@link feign.codec.Encoder}, {@link feign.Contract}.
	 *
	 * @see FeignClientsConfiguration for the defaults
	 */
	Class<?>[] configuration() default {};

	/**
	 * Fallback class for the specified Feign client interface. The fallback class must
	 * implement the interface annotated by this annotation and be a valid spring bean.
	 */
	Class<?> fallback() default void.class;

	/**
	 * Define a fallback factory for the specified Feign client interface. The fallback
	 * factory must produce instances of fallback classes that implement the interface
	 * annotated by {@link FeignClient}. The fallback factory must be a valid spring
	 * bean.
	 *
	 * @see feign.hystrix.FallbackFactory for details.
	 */
	Class<?> fallbackFactory() default void.class;

	/**
	 * Path prefix to be used by all method-level mappings. Can be used with or without
	 * <code>@RibbonClient</code>.
	 */
	String path() default "";

	/**
	 * Whether to mark the feign proxy as a primary bean. Defaults to true.
	 */
	boolean primary() default true;

}

  * Fallback class for the specified Feign client interface. The fallback class must
     implement the interface annotated by this annotation and be a valid spring bean. *

fallback 上会有这样的注释    说的是  声明feign客户端接口 的降级类  而且 这个降级类必须实现 该feign 接口   并且必须是一个可用的spring bean

 如果你仅仅在这个实现类上加入spring bean 声明注解 比如 @Component   你会发现依然 无法注入 来大致猜想一下流程     熟悉springboot 的 应该清楚   springboot  启动的时候  会扫描其main类 所在包的子包进行 bean 实例化     如果不在子包 默认是扫描不到的   那么如何扫描到呢  声明扫描的路径 也就是需要在main类上使用注解@ComponentScan 注解  但是 如果 我们仅仅声明了 feign 降级实现的路径 你会发现 main类的子包无法扫描到了  所以 此处应该 

@ComponentScan(basePackages = {"main 所在的包","降级类所在的包"})

配置好后  我们写一个降级类:

@Component
public class UserServiceHystrix implements UserService {
    @Override
    public User get(User user) {
        System.out.println("<><><><><><><><><><> MEMBER-SERVICE 挂了<><><><><><><><><><> ");
         user.setAge(20017);
         user.setGender("male");
         user.setName("服务挂了");
        return user;
    }
}

 

然后我们测试一下 启动消费方  不启动 提供方MEMBER-SERVICE  发现熔断可用:

 

转载于:https://my.oschina.net/10000000000/blog/1591147

相关文章:

  • Kibana插件sentinl实现邮件报警
  • Vue slot分发内容
  • 前端面试总结(at, md)
  • Webpack入门之遇到的那些坑,系列示例Demo
  • Unity 微型调试器 Debugger
  • CSS文本超出省略
  • 黑客的滑铁卢——美国大断网全纪实
  • 继亚马逊之后,沃尔玛也开始建设无人超市
  • Unity SDK JDK 环境配置 避免各种莫名其妙的报错
  • Idea里面的postfix
  • iOS自定义UIPageControl
  • React-Native flex 布局使用总结
  • Artifactory 如何使用 SHA-256 进行安全存储?
  • weex具体安装教程
  • 中科院2018研究生入学考试 数学分析+高等代数
  • 2019年如何成为全栈工程师?
  • 4个实用的微服务测试策略
  • bootstrap创建登录注册页面
  • C学习-枚举(九)
  • docker容器内的网络抓包
  • Less 日常用法
  • Python 反序列化安全问题(二)
  • python大佬养成计划----difflib模块
  • 爬虫模拟登陆 SegmentFault
  • 前端性能优化——回流与重绘
  • 浅析微信支付:申请退款、退款回调接口、查询退款
  • 如何借助 NoSQL 提高 JPA 应用性能
  • 删除表内多余的重复数据
  • 使用 @font-face
  • 树莓派 - 使用须知
  • 我建了一个叫Hello World的项目
  • 一个6年java程序员的工作感悟,写给还在迷茫的你
  • 一起参Ember.js讨论、问答社区。
  • const的用法,特别是用在函数前面与后面的区别
  • 策略 : 一文教你成为人工智能(AI)领域专家
  • (0)Nginx 功能特性
  • (3)选择元素——(17)练习(Exercises)
  • (超简单)构建高可用网络应用:使用Nginx进行负载均衡与健康检查
  • (二)fiber的基本认识
  • (附源码)ssm考生评分系统 毕业设计 071114
  • (附源码)计算机毕业设计SSM保险客户管理系统
  • (转)创业的注意事项
  • *_zh_CN.properties 国际化资源文件 struts 防乱码等
  • .libPaths()设置包加载目录
  • .net 4.0 A potentially dangerous Request.Form value was detected from the client 的解决方案
  • .NET 反射的使用
  • .net 简单实现MD5
  • .NET 中什么样的类是可使用 await 异步等待的?
  • .net 桌面开发 运行一阵子就自动关闭_聊城旋转门家用价格大约是多少,全自动旋转门,期待合作...
  • .NET/C# 使用 SpanT 为字符串处理提升性能
  • .NET/C# 项目如何优雅地设置条件编译符号?
  • .netcore 如何获取系统中所有session_如何把百度推广中获取的线索(基木鱼,电话,百度商桥等)同步到企业微信或者企业CRM等企业营销系统中...
  • .NET轻量级ORM组件Dapper葵花宝典
  • .NET值类型变量“活”在哪?
  • /boot 内存空间不够