(7) SpringBoot 服務發現(Feign)

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();
 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章