- 远程过程调用RPC
- 接口定义语言(IDL)
- 通讯协议
- Netflix Feign
<!-- 添加 Spring Cloud Feign 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
package com.springcloud.lesson10.api;
import com.springcloud.lesson10.domain.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
/**
* 用户服务
*/
@FeignClient(name = "${user.service.name}") // 利用占位符避免未来整合硬编码
public interface UserService {
/**
* 保存用户
* @param user
* @return
*/
@PostMapping("/user/save")
boolean saveUser(User user);
/**
* 查询所有人
* @return
*/
@GetMapping("/user/find/all")
List<User> findAll();
}
注意,在使用
@FeignClient
name
属性尽量使用占位符,避免硬编码。否则,未来升级时,不得不升级客户端版本。
package com.springcloud.lesson10;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.springcloud.lesson10.api.UserService;
import com.springcloud.lesson10.user.service.client.ping.MyPing;
import com.springcloud.lesson10.user.service.client.rule.MyRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@RibbonClient("user-service-provider") // 指定目标应用名称
@EnableCircuitBreaker // 使用服务短路
@EnableFeignClients(clients = UserService.class) // 申明UserService作为Feign 服务调用
public class UserServiceClientApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceClientApplication.class, args);
}
/**
* 将 {@link MyRule} 暴露成 {@link Bean}
* @return {@link MyRule}
*/
@Bean
public IRule myRule() {
return new MyRule();
}
/**
* 将 {@link MyPing} 暴露成 {@link Bean}
* @return {@link MyPing}
*/
@Bean
public IPing myPing() {
return new MyPing();
}
/**
* 申明具有负载均衡能力的{@link RestTemplate}
* @return
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package com.springcloud.lesson10;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.springcloud.lesson10.api.UserService;
import com.springcloud.lesson10.user.service.client.ping.MyPing;
import com.springcloud.lesson10.user.service.client.rule.MyRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@RibbonClient("user-service-provider") // 指定目标应用名称
@EnableCircuitBreaker // 使用服务短路
@EnableFeignClients(clients = UserService.class) // 申明UserService作为Feign 服务调用
public class UserServiceClientApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceClientApplication.class, args);
}
/**
* 将 {@link MyRule} 暴露成 {@link Bean}
* @return {@link MyRule}
*/
@Bean
public IRule myRule() {
return new MyRule();
}
/**
* 将 {@link MyPing} 暴露成 {@link Bean}
* @return {@link MyPing}
*/
@Bean
public IPing myPing() {
return new MyPing();
}
/**
* 申明具有负载均衡能力的{@link RestTemplate}
* @return
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
调整 application.properties
## 用户ribbon 客户端应用
spring.application.name=user-service-client
## 服务端口
server.port=8080
## 服务提供方
## 服务名称
provider.service.name=user-service-provider
## 服务主机
provider.service.host=localhost
## 服务端口
provider.service.port=9090
## 关闭Eureka Client
eureka.client.enabled=false
user-service-provider.ribbon.listOfServers=\
http://${provider.service.host}:${provider.service.port}
## 扩展IPing实现
user-service-provider.ribbon.NFLoadBalancerPingClassName =\
com.springcloud.lesson10.user.service.client.ping.MyPing
## 配置 @FeignClient(name = "${user.service.name}") 中的占位符
## user.service.name 实际需要指定 UserService 接口的提供方
## 也就是 user-service-provider,可以使用 ${provider.service.name} 替代
user.service.name=${provider.service.name}
调整应用:user-service-provider
package com.springcloud.lesson10.user.service.provider.service;
import com.springcloud.lesson10.api.UserService;
import com.springcloud.lesson10.domain.User;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 内存实现
*/
@Service("inMemoryUserService")
public class InMemoryUserService implements UserService {
private Map<Long, User> repository = new ConcurrentHashMap<>();
@Override
public boolean saveUser(User user) {
return repository.put(user.getId(), user) == null;
}
@Override
public List<User> findAll() {
return new ArrayList<>(repository.values());
}
}
package com.springcloud.lesson10.user.service.web.controller;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.springcloud.lesson10.api.UserService;
import com.springcloud.lesson10.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* 服务提供方
*/
@RestController
public class UserServiceProviderController implements UserService {
@Autowired
@Qualifier("inMemoryUserService")
private UserService userService;
private final static Random random = new Random();
// 通过方法继承,URL 映射: "/user/save"
@Override
public boolean saveUser(@RequestBody User user) {
return userService.saveUser(user);
}
// 通过方法继承,URL 映射: "/user/find/all"
@Override
public List<User> findAll() {
return userService.findAll();
}
/**
* 增加超时处理
* @return
*/
@HystrixCommand(
commandProperties = {
// 设置超时时间返回100ms
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100")
},
fallbackMethod = "fallbackForGetUsers" // 设置fallback方法
)
@GetMapping("/user/list")
public Collection<User> getUsers() throws InterruptedException {
long executeTime = random.nextInt(200);
// 休眠时间
System.out.println("execute time: " + executeTime);
Thread.sleep(executeTime);
return userService.findAll();
}
/**
* {@link #getUsers()} 的fallback方法
* @return
*/
public Collection<User> fallbackForGetUsers() {
return Collections.emptyList();
}
}
package com.springcloud.lesson10.user.service.client.web.controller;
import com.springcloud.lesson10.api.UserService;
import com.springcloud.lesson10.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
*
* {@link UserService} 客户端 {@link RestController}
* 注意: 官方建议客户端和服务端不要同时实现Feign接口
* 这里的代码只是一种说明,实际情况最好使用组合方式,而不是使用继承
* @author <a href="mailto:[email protected]">Finen</a>
* @see
* @since
*/
@RestController
public class UserServiceController implements UserService {
@Autowired
private UserService userService;
// 通过方法继承,URL 映射: "/user/save"
@Override
public boolean saveUser(@RequestBody User user) {
return userService.saveUser(user);
}
// 通过方法继承,URL 映射: "/user/find/all"
@Override
public List<User> findAll() {
return userService.findAll();
}
}
UserService
Fallback 实现
package com.springcloud.lesson10.fallback;
import com.springcloud.lesson10.api.UserService;
import com.springcloud.lesson10.domain.User;
import java.util.Collections;
import java.util.List;
/**
* {@link UserService} Fallback 实现
* @author <a href="mailto:[email protected]">Finen</a>
* @see UserService#saveUser
* @see UserService#findAll()
* @since
*/
public class UserServiceFallback implements UserService {
@Override
public boolean saveUser(User user) {
return false;
}
@Override
public List<User> findAll() {
return Collections.emptyList();
}
}
调整 UserService
@FeignClient
fallback 属性:
package com.springcloud.lesson10.api;
import com.springcloud.lesson10.domain.User;
import com.springcloud.lesson10.fallback.UserServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
/**
* 用户服务
*/
@FeignClient(name = "${user.service.name}", fallback = UserServiceFallback.class) // 利用占位符避免未来整合硬编码
public interface UserService {
/**
* 保存用户
* @param user
* @return
*/
@PostMapping("/user/save")
boolean saveUser(User user);
/**
* 查询所有人
* @return
*/
@GetMapping("/user/find/all")
List<User> findAll();
}
package com.springcloud.lesson10.user.service.web.controller;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.springcloud.lesson10.api.UserService;
import com.springcloud.lesson10.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* 服务提供方
*/
@RestController
public class UserServiceProviderController implements UserService {
@Autowired
@Qualifier("inMemoryUserService")
private UserService userService;
private final static Random random = new Random();
// 通过方法继承,URL 映射: "/user/save"
@Override
public boolean saveUser(@RequestBody User user) {
return userService.saveUser(user);
}
@HystrixCommand(
commandProperties = {
// 设置超时时间返回100ms
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100")
},
fallbackMethod = "fallbackForGetUsers" // 设置fallback方法
)
// 通过方法继承,URL 映射: "/user/find/all"
@Override
public List<User> findAll() {
return userService.findAll();
}
/**
* 增加超时处理
* @return
*/
@HystrixCommand(
commandProperties = {
// 设置超时时间返回100ms
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100")
},
fallbackMethod = "fallbackForGetUsers" // 设置fallback方法
)
@GetMapping("/user/list")
public List<User> getUsers() throws InterruptedException {
long executeTime = random.nextInt(200);
// 休眠时间
System.out.println("execute time: " + executeTime);
Thread.sleep(executeTime);
return userService.findAll();
}
/**
* {@link #getUsers()} 的fallback方法
* @return
*/
public List<User> fallbackForGetUsers() {
return Collections.emptyList();
}
}
<dependencies>
<!-- Eureka Server 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</dependencies>
package com.springcloud.lesson10.eurreka.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @author <a href="mailto:[email protected]">Finen</a>
* @see
* @since
*/
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
## 配置服务器应用名称
spring.application.name = eureka-server
## 配置服务器端口
server.port = 10000
# 启用端点 env
management.endpoint.env.enabled=true
# 暴露端点 env 配置多个,隔开
management.endpoints.web.exposure.include=*
## Spring Cloud Eureka 服务器作为注册中心
## 通常情况下,不需要再注册到其他注册中心去
## 同时,它也不需要获取客户端信息
### 取消向注册中心注册
eureka.client.register-with-eureka = false
### 取消向注册中心获取注册信息(服务、实例信息)
eureka.client.fetch-registry = false
## 解决 Peer / 集群 连接问题
eureka.instance.hostname = localhost
eureka.client.serviceUrl.defaultZone = http://${eureka.instance.hostname}:${server.port}/eureka
端口信息
user-service-client : 8080
user-service-provider: 9090
eureka-server : 10000
配置应用:user-service-client
<!-- 依赖 Spring Cloud Netflix Eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
UserServiceClientApplication.java
package com.springcloud.lesson10;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.IRule;
import com.springcloud.lesson10.api.UserService;
import com.springcloud.lesson10.user.service.client.ping.MyPing;
import com.springcloud.lesson10.user.service.client.rule.MyRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@RibbonClient("user-service-provider") // 指定目标应用名称
@EnableCircuitBreaker // 使用服务短路
@EnableFeignClients(clients = UserService.class) // 申明UserService作为Feign 服务调用
@EnableDiscoveryClient // 激活服务发现
public class UserServiceClientApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceClientApplication.class, args);
}
/**
* 将 {@link MyRule} 暴露成 {@link Bean}
* @return {@link MyRule}
*/
@Bean
public IRule myRule() {
return new MyRule();
}
/**
* 将 {@link MyPing} 暴露成 {@link Bean}
* @return {@link MyPing}
*/
@Bean
public IPing myPing() {
return new MyPing();
}
/**
* 申明具有负载均衡能力的{@link RestTemplate}
* @return
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
application.properties
## 用户ribbon 客户端应用
spring.application.name=user-service-client
## 服务端口
server.port=8080
## 服务提供方
## 服务名称
provider.service.name=user-service-provider
## 服务主机
provider.service.host=localhost
## 服务端口
provider.service.port=9090
## 激活 Eureka Client
eureka.client.enabled=true
user-service-provider.ribbon.listOfServers=\
http://${provider.service.host}:${provider.service.port}
## 扩展IPing实现
user-service-provider.ribbon.NFLoadBalancerPingClassName =\
com.springcloud.lesson10.user.service.client.ping.MyPing
## 配置 @FeignClient(name = "${user.service.name}") 中的占位符
## user.service.name 实际需要指定 UserService 接口的提供方
## 也就是 user-service-provider,可以使用 ${provider.service.name} 替代
user.service.name=${provider.service.name}
## Spring Cloud Eureka 客户端 注册到 Eureka 服务器
eureka.client.serviceUrl.defaultZone = http://localhost:10000/eureka
配置应用:user-service-provider
<!-- 依赖 Spring Cloud Netflix Eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
UserServiceProviderApplication.java
package com.springcloud.lesson10;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
@SpringBootApplication
@EnableHystrix
@EnableDiscoveryClient
public class UserServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceProviderApplication.class, args);
}
}
application.properties
## 用户服务提供方应用信息
spring.application.name = user-service-provider
## 服务端口
server.port = 9090
## Spring Cloud Eureka 客户端 注册到 Eureka 服务器
eureka.client.serviceUrl.defaultZone = http://localhost:10000/eureka
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
注意:user-service-client application.properties 中以下内容将会被配置服务器中的 user-service.properties 替代.
## 服务提供方 ## 服务名称 provider.service.name=user-service-provider ## 服务主机 provider.service.host=localhost ## 服务端口 provider.service.port=9090 ## 配置 @FeignClient(name = "${user.service.name}") 中的占位符 ## user.service.name 实际需要指定 UserService 接口的提供方 ## 也就是 user-service-provider,可以使用 ${provider.service.name} 替代 user.service.name=${provider.service.name}
创建 user-service.properties
## User Service 配置内容
## 提供方服务名称
provider.service.name = user-service-provider
## 提供方服务主机
provider.service.host = localhost
## 提供方服务端口
provider.service.port = 9090
## 配置 @FeignClient(name = "${user.service.name}") 中的占位符
## user.service.name 实际需要制定 UserService 接口的提供方
## 也就是 user-service-provider,可以使用 ${provider.service.name} 替代
user.service.name = ${provider.service.name}
目前${user.dir} 指向:E:\JavaProjects\JavaStudySpace\springcloud-lesson\lesson10>
user-service.properties
相对于 /config-server/src/main/resources/configs
控制台执行 git 命令:
git init
Initialized empty Git repository in E:/JavaProjects/JavaStudySpace/springcloud-lesson/lesson10/config-server/src/main/resources/configs/.git/
$ git add user-service.properties
application.properties
## Spring Cloud Config Server 应用名称
spring.application.name=config-server
## 服务器服务端口
server.port = 7070
# 启用端点 env
management.endpoint.env.enabled=true
# 暴露端点 env 配置多个,隔开
management.endpoints.web.exposure.include=*
## Spring Cloud Eureka 客户端 注册到 Eureka 服务器
eureka.client.serviceUrl.defaultZone = http://localhost:10000/eureka
## 配置服务器文件系统git 仓库
## ${user.dir} 减少平台文件系统的不一致
## 目前 ${user.dir}/config-server/src/main/resources/configs
spring.cloud.config.server.git.uri = ${user.dir}/config-server/src/main/resources/configs
pom.xml
<!-- 依赖 Spring Cloud Netflix Eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
application.properties
## Spring Cloud Eureka 客户端 注册到 Eureka 服务器
eureka.client.serviceUrl.defaultZone = http://localhost:10000/eureka
激活服务发现
package com.springcoud.lesson.config.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
/**
* 配置服务器应用
* @author <a href="mailto:[email protected]">Finen</a>
* @see
* @since
*/
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
调整应用 user-service-client
,作为 config-client 应用
<!-- 依赖 Spring Cloud Config Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
bootstrap.properties
## 用户ribbon 客户端应用
spring.application.name=user-service-client
## Spring Cloud Eureka 客户端 注册到 Eureka 服务器
eureka.client.serviceUrl.defaultZone = http://localhost:10000/eureka
spring.cloud.config.name=user-service
spring.cloud.config.profile=default
spring.cloud.config.label=master
spring.cloud.config.fail-fast=true
## 激活 Config 服务器发现
spring.cloud.config.discovery.enabled=true
## 配置 Config 服务器的应用名称(Service ID)
spring.cloud.config.discovery.serviceId=config-server
application.properties 也有调整
## 服务端口
server.port=8080
## 激活 Eureka Client
eureka.client.enabled=true
## 扩展IPing实现
user-service-provider.ribbon.NFLoadBalancerPingClassName =\
com.springcloud.lesson10.user.service.client.ping.MyPing
## 以下内容由Config Server提供
### 服务提供方
### 服务名称
#provider.service.name=user-service-provider
### 服务主机
#provider.service.host=localhost
### 服务端口
#provider.service.port=9090
#
### 配置 @FeignClient(name = "${user.service.name}") 中的占位符
### user.service.name 实际需要指定 UserService 接口的提供方
### 也就是 user-service-provider,可以使用 ${provider.service.name} 替代
#user.service.name=${provider.service.name}