上一个文章介绍了如何搭建一个 消费者 eureka client,如何注册到server,这篇文章介绍如何消费。
一般情况下有2种方式:一种是ribbon+restTemplate,另一种是feign,来调用服务
1、 ribbon+restTemplate
这里需要注意的就是负载均衡
2、feign
2.1、pom.xml添加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">
<parent>
<groupId>cn.dails</groupId>
<artifactId>dails-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath></relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>dms-asset</artifactId>
<name>dms-asset 客户资产</name>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
<build>
<finalName>dms-asset</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2、添加一个接口FeignClient
package cn.dms.service.feignClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "dms-user")
public interface UserService {
@RequestMapping(value = "/user/private/findUser",method = RequestMethod.GET)
String findUser(@RequestParam(value = "name") String name);
}
2.3、启动类添加@EnableFeignClients
package cn.dms;
import cn.dms.service.feignClient.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@RestController
public class AssetApplication {
public static void main(String[] args) {
SpringApplication.run( AssetApplication.class, args );
}
@Value("${server.port}")
String port;
@Autowired
UserService userInterface;
@RequestMapping("/hello")
public String home(@RequestParam(value = "name", defaultValue = "屌丝") String name) {
return userInterface.findUser("屌丝");
}
}