一、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
feign:
hystrix:
enabled: true # feign自带熔断器,默认是关闭的,需要手动开启
三、启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
@EnableFeignClients
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
四、服务调用
/**
* feign服务调用示例
*
*/
@FeignClient(value = "service-hi",fallback = HelloServiceImpl.class) //配置feign自带熔断器,fallback指定熔断后调用方法
public interface IHelloService {
/**
* 调用服务
*
* @param name
* @return
*/
@RequestMapping(value = "/hi", method = RequestMethod.GET)
String sayHi(@RequestParam("name") String name);
}
/**
* Feign 熔断服务实现
*
*/
@Component
public class HelloServiceImpl implements IHelloService {
@Override
public String sayHi(String name) {
return "sorry " + name;
}
}
五、控制器调用服务
/**
* feign远程调用
*
*/
@RestController
public class HiController {
@Autowired
private IHelloService helloService;
@GetMapping(value = "/hi")
public String sayHi(@RequestParam String name) {
return helloService.sayHi(name);
}
}
网友评论