1. 程式人生 > >Using ribbon and feign without eureka or both

Using ribbon and feign without eureka or both

需求描述

有三個服務A、B、C,A和B在一個註冊中心,C是一個獨立的SpringBoot服務。關係如下
在這裡插入圖片描述
即服務B需要同時通過註冊中心訪問A,和不通過註冊中心訪問C。使用RestTemplate也可以做到,但是這不是我們想要的效果。既然已經集成了feign這個強大的客戶端工具,就必須用起來啊。

實現方法

@Configuration
@RibbonClient(name = "custom", configuration = CustomConfiguration.class)
public class TestConfiguration {
}

注意下面這段話

The CustomConfiguration clas must be a @Configuration class, but take care that it is not in a @ComponentScan for the main application context.

CustomConfiguration必須有@Configuration註解,並且不在@ComponentScan配置的掃描包中。如果直接使用的@SpringBootApplication那麼不能和應用啟動類在同一個包或其下級包下。

先寫一個例項

// com.wawscm.cloud.online.Application

@SpringBootApplication(scanBasePackages = "com.wawscm.cloud.online")
@EnableTransactionManagement
@EnableWebMvc
@EnableEurekaClient
@EnableFeignClients
@MapperScan("com.wawscm.cloud.online.mapper") @RibbonClients({ @RibbonClient(name = "custom", configuration = CustomRibbonClientConfiguration.class) }) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
// com.wawscm.cloud.ribbon.CustomRibbonClientConfiguration
@Configuration public class CustomRibbonClientConfiguration{ @Bean public ILoadBalancer ribbonLoadBalancer() { BaseLoadBalancer balancer = new BaseLoadBalancer(); balancer.setServersList(Arrays.asList(new Server("localhost", 8229))); return balancer; } }

定義一個Feign客戶端。

@FeignClient(name = "custom") // 與上面配置的RibbonClient中的name一致
public interface CustomFeignClient {
	
	@GetMapping("/hello")
	String hello(@RequestParam("name") String name)
}

// 使用
@RestController
public class CustomController {
	@Autowired
	private CustomFeignClient client;

	@GetMapping("/sayHi")
	public String (String name) {
		this.client.hello(name);
	}
}

使用上面的方法就可以相容註冊中心服務和非註冊中心服務兩種模式了。在專案中服務的地址應配置在配置檔案中。