【Eureka】服务发现调用

【Eureka】服务发现调用

转载:https://www.cnblogs.com/yangchongxing/p/10779832.html

1、使用 Netfix Feign 客户端调用服务

首先引入 spring-cloud-starter-openfeign 依赖,那个工程使用那个工程就引用

<?xml version="1.0" encoding="UTF-8"?>
<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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ycx</groupId>
    <version>0.0.1-SNAPSHOT</version>
    <artifactId>demo-server</artifactId>
    <name>demo-server</name>
    <description>sc server</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>ycx</groupId>
            <artifactId>common-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <!-- spring boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <!-- spring cloud -->
        <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>

        <!-- other -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>

</project>

其次使用 @FeignClient 定义接口和实现,也就是被调用者

接口,注意:一定要指定 value 或 name,其值是注册服务的应用名, @FeignClient(value = "common-server")

package ycx.common.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ycx.common.bean.Result;

@FeignClient(value = "common-server")
@RequestMapping("/common/feign")
public interface CommonFeign {

    @GetMapping("/info")
    Result<String> info();
}

实现

package ycx.common.feign.impl;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestController;
import ycx.common.bean.Result;
import ycx.common.feign.CommonFeign;

@RestController
public class CommonFeignImpl implements CommonFeign {
    @Override
    public Result<String> info() {
        Result<String> result = new Result<>();
        result.setStatus(String.valueOf(HttpStatus.OK.value()));
        result.setMessage(HttpStatus.OK.getReasonPhrase());
        result.setData("Common");
        return result;
    }
}

接口端 pom

<?xml version="1.0" encoding="UTF-8"?>
<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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ycx</groupId>
    <version>0.0.1-SNAPSHOT</version>
    <artifactId>common-api</artifactId>
    <name>common-api</name>
    <description>sc server</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>ycx</groupId>
            <artifactId>common-api</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <!-- spring boot -->

        <!-- spring cloud -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <!-- other -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>
</project>

再次调用者启动类使用 @EnableFeignClients 注解客户端,注意:指定扫描的包

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients({"ycx.*.feign"})
@RestController
public class DemoServerApplication 

最后使用接口调用服务

package ycx.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ycx.common.bean.Result;
import ycx.common.feign.CommonFeign;

import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient   //可不写
@EnableFeignClients({"ycx.common.feign"})
@RestController
public class DemoServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoServerApplication.class, args);
    }

    @Autowired
    CommonFeign commonFeign;

    @GetMapping("/fn")
    public Result<String> fn() {
        return commonFeign.info();
    }
}

2、使用带有 Ribbon 功能的 RestTemplate 调用服务

必须使用 @LoadBalanced 标注 RestTemplate Bean

@LoadBalanced
@Bean
public RestTemplate getRestTemplate() {
    return new RestTemplate();
}
/**
 * 使用带有 Ribbon 功能的 RestTemplate 访问服务
 * @return
 */
@GetMapping("/rest")
public Result<String> rest() {
    ResponseEntity<Result> restExchange = restTemplate.exchange(
            "http://common-server/",
            HttpMethod.GET, null, Result.class);
    return restExchange.getBody();
}

3、使用 DiscoveryClient 和 普通 RestTemplate 调用服务

@Autowired
DiscoveryClient discoveryClient;


/**
 * 使用 DiscoveryClient 查找服务,使用标准的 RestTemplate 访问服务
 */
@GetMapping("/")
public Result<String> ok() {
    List<ServiceInstance> instanceList = discoveryClient.getInstances("common-server");
    if(CollectionUtils.isEmpty(instanceList)) {
        Result<String> result = new Result<>();
        result.setStatus(String.valueOf(HttpStatus.NOT_FOUND));
        result.setMessage(HttpStatus.NOT_FOUND.getReasonPhrase());
        return result;
    } else {
        RestTemplate restTemplate = new RestTemplate();
        String uri = instanceList.get(0).getUri().toString();
        ResponseEntity<Result> restExchange =
                restTemplate.exchange(uri, HttpMethod.GET, null, Result.class);
        return restExchange.getBody();
    }
}
原文地址:https://www.cnblogs.com/yangchongxing/p/10779832.html