Feign整合了Ribbon和Hystrix(关于Hystrix我们后面再讲),可以让我们不再需要显式地使用这两个组件。
总起来说,Feign具有如下特性:
废话不多,下面是一个案例:
pom配置文件,feign自带了ribbion.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
编写接口,与服务相对应
import com.boss.bossxtrainauthentication.feign.impl.SchedualServiceLoginHystric;
import com.boss.bossxtrainauthentication.pojo.vo.UserVO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "boss-xtrain-system",fallback = SchedualServiceLoginHystric.class)
public interface SchedualServiceLogin {
@RequestMapping(value = "/loadUserByUsername",method = RequestMethod.GET)
UserVO loadUserByUsername(@RequestParam(value = "name", defaultValue = "weng") String name);
}
其中boss-xtrain-system为需要调用微服务的名称,SchedualServiceLoginHystric为熔断后的类,该类中给每个接口都定义了返回,返回不同的异常或信息。SchedualServiceLogin 类中的方法和微服务中的方法相对应
@Autowired
SchedualServiceLogin schedualServiceLogin;
//调用语句。
userVO = schedualServiceLogin.loadUserByUsername(username);
使用时,自动注入,这里idea会警告找不到实现类,不要紧,因为这是运行时注入的。
UserVO是我自定义的类,大家可以按照微服务返回的类型自定义。另外需要远程传输的类一定要序列化,否则在接收时会报错。
。
import com.boss.bossxtrainauthentication.feign.SchedualServiceLogin;
import com.boss.bossxtrainauthentication.pojo.vo.UserVO;
import com.boss.xtrain.common.exception.logging.exception.BussinessException;
import com.boss.xtrain.common.exception.logging.exception.ExceptionEnums;
import org.springframework.stereotype.Component;
@Component
public class SchedualServiceLoginHystric implements SchedualServiceLogin {
@Override
public UserVO loadUserByUsername(String name) {
//100301,登入服务出现错误,。 103开头是认证授权里的异常
throw new BussinessException(ExceptionEnums.BUSINESS_USER_DICTIONARY_ADD_EXCEPTION,new Throwable());
}
}