【SpringCloud】(十四):Feign对Hystrix的支持 fallbackFactory

  前面的文章中提到了fallback,这里我们描述一个它的增强版。fallbackFactory。都是实现断路器的功能。


【SpringCloud】(十四):Feign对Hystrix的支持 fallbackFactory_第1张图片



UserFeignClient

package com.dynamic.cloud.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.dynamic.cloud.entity.User;

//@FeignClient(name="microservice-provider-user",fallback =HystrixClientFallback.class,fallbackFactory=HystrixClientFallbackFactory.class)
@FeignClient(name="microservice-provider-user",fallbackFactory=HystrixClientFallbackFactory.class)
public interface UserFeignClient {
	
	@RequestMapping(value="/simple/{id}",method = RequestMethod.GET) //只能是RequestMapping
	public User findById(@PathVariable("id") Long id); //@PathVariable需要设置括号中的名称

}


加上fallbackFactory

对应的类是HystrixClientFallbackFactory 


package com.dynamic.cloud.feign;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.dynamic.cloud.entity.User;
import feign.hystrix.FallbackFactory;

@Component
public class HystrixClientFallbackFactory implements FallbackFactory {

	private static final Logger logger = LoggerFactory.getLogger(HystrixClientFallbackFactory.class);
	@Override
	public UserFeignClient create(Throwable cause) {
		HystrixClientFallbackFactory.logger.info("fallback reason was: {} " ,cause.getMessage());
		
		return new UserFeignClientWithFactory()
				{
					@Override
					public User findById(Long id) {
						User user = new User();
						user.setId(-1L);
						return user;
					}
				};
	}
}


该类中存在UserFeignClientWithFactory,它继承了UserFeignClient。这里实现了它的方法。

package com.dynamic.cloud.feign;

public interface UserFeignClientWithFactory extends UserFeignClient {
}


  我们把用户微服务停掉之后,断路器打开,执行fallbackfactory 指定的类中方法。HystrixClientFallbackFactory 。

      【SpringCloud】(十四):Feign对Hystrix的支持 fallbackFactory_第2张图片

你可能感兴趣的:(SpringCloud)