spring cloud 微服务应用间通信

SpringCloud 应用间通讯基于HTTP的Restful调用方式有两种,RestTemplate与Feign。java

1.RestTemplate应用间通信spring

经过 @LoadBalanced,可在restTemplate 直接使用应用名字。app

@Component
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    
}
    @Autowired
    private RestTemplate restTemplate;
    
    @Override
    public String hello() {
        //使用RestTemplate通信调用auth-server服务
        String url="http://auth-server/hello";
        //返回值类型和咱们的业务返回值一致
        return restTemplate.getForObject(url, String.class);
    }

2.Feign应用间通信ide

引入依赖注意要加版本号,不然引入依赖可能失败url

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.2.RELEASE</version>
</dependency>

启动类须要增长注解@EnableFeignClientsspa

@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class ManagerServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ManagerServerApplication.class, args);
    }
}

须要编写接口声明
@FeignClient参数注解代表这个是Fegin客户端,name参数指定访问的服务网关rest

@FeignClient(name = "auth-server")//服务网关
public interface TestClient {

    @RequestMapping("/fegin/hello")//调用的服务
    String feginHello();
}

调用code

    @Autowired
    private TestClient testClient;

    @Override
    public String feginHello() {
        //使用fegin通信调用auth-server服务
        return testClient.feginHello();
    }
相关文章
相关标签/搜索