1.创建springcloud-consumer jar项目
详细过程参照上一篇springcloud-eureka的创建过程,此处略)
2.修改pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.dongjin.springcloud</groupId>
<artifactId>springcloud-root</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>springcloud-consumer</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
</project>
3.springboot的启动程序ConsumerApplication.java
使用FeignClient调用服务提供者
package com.dongjin.springcloud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class ConsumerApplication {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(ConsumerApplication.class, args);
}
@FeignClient(value = "springcloud-user")
public interface FeiHiService {
@RequestMapping(value = "/hi")
String sayHi();
}
@RestController
public class FeiHiController {
@Autowired
FeiHiService hiService;
@RequestMapping("/hello")
public String sayHello(String name){
String word = hiService.sayHi();
return word;
}
}
}
4.在resources目录下追加application.yml
server:
port: 8002
spring:
application:
name: springcloud-consumer
eureka:
instance:
instance-id: springcloud-consumer
appname: ${spring.application.name}
client:
service-url:
defaultZone: http://localhost:8888/eureka/
6.用run as运行ConsumerApplication.java程序后,访问http://localhost:8002/hello,看到以下页面,证明消费者调用服务提供者启动成功