刚才服务的提供者,提供了一个连接为http://localhost:8003/hello的一个资源.且已经在注册中心成功注册.
所以接下来就可以写调用者了.
同样的,新建一个maven项目,然后将之前的pom.xml 内的依赖拿过来,在dependencies中再加上一个spring-cloud-starter-feign的依赖,如下所示.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
等待jar包下载完成,就可以开始写调用方法了.
先写一个针对于提供者的rest服务的接口.
我们知道提供者的资源uri 是"/hello",提供者的application name 是"spring-cloud-provider"
package com.example.demo;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name="spring-cloud-provider")
public interface HelloProvider {
@RequestMapping(value = "/hello")
public String hello(@RequestParam(value = "name") String name);
}
将这个bean 注入到control中,像普通的访问方式进行访问即可.
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloControl {
@Autowired
HelloProvider HelloProvider;
@RequestMapping("/hello/{name}")
public String index(@PathVariable("name") String name) {
return HelloProvider.hello(name);
}
}
然后在启动类上加上@EnableDiscoveryClient ,@EnableFeignClients 这 两个注解.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
最后配置一下application.properties
spring.application.name=spring-cloud-caller
server.port=8002
eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
启动项目,输入http://localhost:8002/hello/xxx, 即可看到返回内容:
你好! 火车呢,这是第一条消息!