Consul call services (Consumer Services)
Dependencies
Add a dependency in the spring-cloud-consul-client project, POM contents of the file add the following dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
spring-cloud-starter-consul-discovery provide support for the Consul, spring-cloud-starter-openfeign provide Feign style calls for the HTTP request, spring-boot-starter-web just to test the use of HTTP MVC convenient.
Configuration information
spring.application.name=spring-cloud-consul-client
server.port=9002
spring.cloud.consul.host=127.0.0.1
spring.cloud.consul.port=8500
#设置不需要注册到 consul 中
spring.cloud.consul.discovery.register=false
This test need not register themselves to the service center: spring.cloud.consul.discovery.register = false, so do not start class declaration @EnableDiscoveryClient notes.
Remote service call interface
@FeignClient(name= "service-provider")
public interface ServiceProviderRemote {
@RequestMapping("/hello")
public String Hello(@RequestParam String name);
}
Use openfeign call the remote service interface, openfeign is Feign after the Spring package, this project openfeign need to use spring-cloud-starter-consul-discovery.
Consumer Testing Services Interface
@RestController
public class TestConsul {
@Autowired
ServiceProviderRemote remote;
@RequestMapping("/TestHello")
public String TestHello(){
String first = remote.Hello("first-SWS");
String second = remote.Hello("second-SWS");
return first + " | " + second;
}
@RequestMapping("/Test")
public String Test(){
return "OK";
}
}
To test load balancing so called twice service interface.
Startup class
@SpringBootApplication
@EnableFeignClients
public class SpringCloudConsulClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudConsulClientApplication.class, args);
}
}
You need to use @EnableFeignClients annotation start openfeign start class.
Start test project
Access http://127.0.0.1:9002/TestHello see the results:
Source
Github repository: https: //github.com/sunweisheng/spring-cloud-example