【SpringCloud】(十四):Feign對Hystrix的支援 fallbackFactory

00潤物無聲00發表於2017-08-14

  前面的文章中提到了fallback,這裡我們描述一個它的增強版。fallbackFactory。都是實現斷路器的功能。





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<UserFeignClient> {

	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 。

      

相關文章