版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuxiaoxiaosmile/article/details/82971960
Feign和RestTemplate的服务注册相同
1. Feign依赖包spring-cloud-starter-ribbon
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
#还包括“SpringBoot 服务注册”中的两个依赖:
#spring-boot-starter-actuator
#spring-cloud-starter-consul-discovery
#Feign默认集成了ribbon
2. SpringBoot入口类中添加代码如下:
package com.ethan.example.client;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@EnableDiscoveryClient //服务注册
@EnableFeignClients //服务发现
@SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args); //重要
}
}
3. 使用示例
//1)控制器
package com.ethan.example.client.controller;
import com.ethan.example.client.feign.ProjectServiceFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(description = "Feign Test Service Found")
@RestController
@RequestMapping("/feign")
public class FeignServiceFundController {
Logger logger = LoggerFactory.getLogger(FeignServiceFundController.class);
@Autowired
private ProjectServiceFeign projectService;
@GetMapping("/find")
@ApiOperation(value = "Make Service Found")
public String makeFound() {
logger.info("test service found begin...");
String result = projectService.getHelloWorld();
return result;
}
}
//2)服务,访问GET http://example:server-port/example/project/hello
package com.ethan.example.client.feign;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(name = "example") //访问的服务名称
@RequestMapping("/example")
public interface ProjectServiceFeign {
@RequestMapping(value = "/project/hello", method = RequestMethod.GET)
public String getHelloWorld();
}