spring cloud 微服务应用间通讯

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

1.RestTemplate应用间通讯

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

@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应用间通讯

引入依赖注意要加版本号,否则引入依赖可能失败

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

启动类需要增加注解@EnableFeignClients

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

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

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

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

调用

    @Autowired
    private TestClient testClient;

    @Override
    public String feginHello() {
        //使用fegin通讯调用auth-server服务
        return testClient.feginHello();
    }

 

posted on 2019-02-13 16:51  惊涛随笔  阅读(630)  评论(0编辑  收藏  举报

导航