一、maven配置
<groupId>com.wk.sc</groupId>
<artifactId>springcloud-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
<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-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
二、application.yml配置
server:
port: 7071
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: service-feign
三、启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
@EnableFeignClients
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
四、服务调用
/**
* feign服务调用示例
*
*/
@FeignClient(value = "service-hi")
public interface IHelloService {
/**
* 调用服务
*
* @param name
* @return
*/
@RequestMapping(value = "/hi", method = RequestMethod.GET)
String sayHi(@RequestParam("name") String name);
}
只需要提供接口并调用服务就可以了
五、控制器调用服务
/**
* feign远程调用
*
*/
@RestController
public class HiController {
@Autowired
private IHelloService helloService; //忽略IDE spring注入错误,该服务是在运行时注入的,所以项目未启动spring是没办法感知的
@GetMapping(value = "/hi")
public String sayHi(@RequestParam String name) {
return helloService.sayHi(name);
}
}
网友评论