一、工具及说明
开发工具:IntelliJ IDEA 2018.2.2 (Ultimate Edition)
框架:spring boot 2.0.8、spring cloud Finchley.SR2
以通用户ID获取用户信息为例,搭建一套spring cloud微服务系统。
需要搭建一个父工程spring-cloud,一个服务注册中心eureka-server,两个微服务cloud-client,cloud-provider。
两个微服务均注册到服务注册中心。
二、微服务消费方的搭建
消费方cloud-client的搭建,基本和服务方cloud-provider一样,还是写全吧。
-
File—>New—>Module
-
选择Spring Initializr,选择对应的JDK,
Choose Initializr Server URL 选择 default。
Next。
-
输入项目组Group:com.cloud。
组件名称Artifact:cloud-client。
Type:选择Maven Project。
修改自动生成的Package。
Next。
-
dependencies选择Cloud Discovery—>Eureka Discovery,Cloud Routing—>Feign。
Spring Boot选择你需要的版本,我这选择2.0.8。
Next。
-
Project Name一般不做修改,和组件名称Artifact一样。
Content root、Module file location 均按自动生成,不做修改。
Finish。
-
配置。
将自动生成的application.properties更改为application.yml文件,个人习惯使用yml文件。
rename的快捷键是Shift+F6。
在application.yml中加入以下配置:server: port: 8082 spring: application: name: cloud-client eureka: client: serviceUrl: defaultZone: http://user:123456@localhost:8080/eureka/ #服务注册中信地址,含有BASIC认证的用户名和密码 instance: prefer-ip-address: true #将IP注册到服务注册中心 #放开所有节点 management: endpoints: web: exposure: include: '*'
-
修改pom文件。
可以发现,pom文件中已自动引入了Eureka客户端、Feign模块依赖。
将按以下修改,使用父工程spring-cloud的spring boot依赖。
如果需要使用/health进行健康检查,则加入健康检查模块。
如果需使用Tomcat运行,需要加入tomcat支持模块和web模块。<?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> <!-- 引入父工程的spring boot依赖 --> <parent> <groupId>com.cloud</groupId> <artifactId>spring-cloud</artifactId> <version>1.0</version> </parent> <groupId>com.cloud</groupId> <artifactId>cloud-client</artifactId> <version>0.0.1-SNAPSHOT</version> <name>cloud-client</name> <description>Demo project for Spring Boot</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Finchley.SR2</spring-cloud.version> </properties> <dependencies> <!--web依赖--> <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.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--Feign模块--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- tomcat支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </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>
-
启动类CloudClientApplication 。
在启动类上加入@EnableDiscoveryClient注解,声明该微服务注册到服务注册中心。
加入@EnableFeignClients,声明使用Feign调用接口。import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EnableFeignClients @EnableDiscoveryClient @SpringBootApplication public class CloudClientApplication { public static void main(String[] args) { SpringApplication.run(CloudClientApplication.class, args); } }
-
使用Tomcat启动,需创建类ServletInitializer。
import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(CloudClientApplication .class); } }
-
创建获取用户信息的接口,并请求服务提供方cloud-provider
10.1 项目结构
10.2 UserControllerimport com.cloud.client.user.entity.User; import com.cloud.client.user.feign.UserFeignClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserFeignClient userFeignClient; @GetMapping("/user/{id}") public User findById(@PathVariable Long id) { User user = this.userFeignClient.findById(id); return user; } }
10.3 User
public class User { private Long id; private String username; private String name; private Integer age; private Double balance; private String requestId; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public Double getBalance() { return this.balance; } public void setBalance(Double balance) { this.balance = balance; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } }
10.4 UserFeignClient
import com.cloud.client.user.entity.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import feign.hystrix.FallbackFactory; @FeignClient(name = "cloud-provider", fallbackFactory = FeignClientFallbackFactory.class) public interface UserFeignClient { @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User findById(@PathVariable("id") Long id); } /** * UserFeignClient的fallbackFactory类,该类需实现FallbackFactory接口,并覆写create方法 */ @Component class FeignClientFallbackFactory implements FallbackFactory<UserFeignClient> { private static final Logger LOGGER = LoggerFactory.getLogger(FeignClientFallbackFactory.class); @Override public UserFeignClient create(Throwable cause) { return new UserFeignClient() { @Override public User findById(Long id) { FeignClientFallbackFactory.LOGGER.info("fallback; reason was:", cause); User user = new User(); user.setId(-1L); user.setUsername("默认用户"); user.setAge(0); user.setBalance((double) 0); return user; } }; } }