目标:在微服务 A 中调用微服务 B 中的接口
添加 Ribbon 与 OpenFeign 的依赖 (1)由于 nacos-discovery 已包含了 Ribbon,因此无需引入该依赖 (2)但从 2022.0.1 版本的 Spring Cloud 开始,需要引入 loadbalancer 才能使用 LoadBalanced 的注解 (3)因此只需要单独引入 OpenFeign 的依赖
创建 RestTemplate 配置类,将 RestTempleate 纳入 Spring 管理,才能实现自动注入 Autowire import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* RibbonConfig
*/
@Configuration
public class RibbonConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
在 Application 启动类中启用 Feign 的注解 import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class AServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AServiceApplication.class, args);
}
}
创建一个 Service 接口,用于调用微服务 B 的接口 import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.entity.SampleObject;
@FeignClient(value="b-service")
public interface BServiceService {
@GetMapping("/sample")
SampleObject getSampleObject();
}
在 Controller 类接口中调用该服务的接口
@Autowired
BServiceService bServiceService;
@GetMapping("sampleobj")
public SampleObject getSampleObject() {
return bServiceService.getSampleObject();
}
精彩内容
发表评论