springcloud(四) ribbon和feign
Ribbon使用
order-service工程:

application.yml:
server:
port: 9010 #order 服务都是用90 开头的端口
spring:
application:
name: microservice-consumer-order
eureka:
client:
serviceUrl:
defaultZone: http://peer1:8761/eureka/
instance:
prefer-ip-address: true
pom.xml:
<?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>
<groupId>com.tuling.cloud</groupId>
<artifactId>microservice-consumer-order-ribbon</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>05-ms-consumer-order-ribbon</name> <!-- 引入spring boot的依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency> <!-- 已经包含了ribbon包-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies> <!-- 引入spring cloud的依赖 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <!-- 添加spring-boot的maven插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
ConsumerOrderApplication.java:
package com.jiagoushi.cloud.study; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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; /**
* 演示默认的轮询的负载均衡
*/
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerOrderApplication { @Bean
@LoadBalanced //ribbon的负载均衡注解,RestTemplate就具有了负载均衡
public RestTemplate restTemplate() {
return new RestTemplate();
} public static void main(String[] args) {
SpringApplication.run(ConsumerOrderApplication.class, args);
}
}
OrderController.java
package com.jiagoushi.cloud.study.user.controller; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import com.jiagoushi.cloud.study.user.entity.User; import java.util.HashMap;
import java.util.Map; @RestController
public class OrderController { private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class); @Autowired
private RestTemplate restTemplate; @Autowired
private LoadBalancerClient loadBalancerClient; @GetMapping("/order")
public Map testOrder() {
Map<String ,Object> map = new HashMap<>();
map.put("测试服务是否启动","ok");
return map;
} @GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
} @GetMapping("/user/getIpAndPort")
public String getIpAndPort() {
return this.restTemplate.getForObject("http://microservice-provider-user/getIpAndPort", String.class);
} @GetMapping("/log-user-instance")
public void logUserInstance() {
ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user");
// 打印当前选择的是哪个节点
OrderController.LOGGER.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
}
}
启动order服务调用user服务的时候就是采用了轮询。
user-service 工程:

UserController.java:
package com.jiagoushi.cloud.study.controller; import com.jiagoushi.cloud.study.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController; import java.util.HashMap;
import java.util.Map; @RestController
public class UserController { @Autowired
private UserRepository userRepository; @Autowired
private Registration registration; @GetMapping("/user")
public Map testUser() {
Map<String,Object> map = new HashMap<>();
map.put("测试user服务","OK");
return map;
} @GetMapping("/{id}")
public com.jiagoushi.cloud.study.entity.User findById(@PathVariable Long id) {
com.jiagoushi.cloud.study.entity.User findOne = userRepository.findOne(id);
return findOne;
} @GetMapping("/getIpAndPort")
public String findById() {
return registration.getHost() + ":" + registration.getPort();
}
}

分别改为 8001 和 8002 端口启动,注册中心别忘了启动
注意:
测试结果:

发现order服务是轮询调用user服务的。
在配置文件可以指定某个服务使用Ribbon某个策略:

Ribbon脱离Eureka独立使用

Ribbon配置的优先级:属性配置 > JAVA配置(注解和配置类)>Netflix Ribbon默认配置
Feign使用
order-feign工程:

order 服务pom.xml 添加依赖:
<?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>
<groupId>com.tuling.cloud</groupId>
<artifactId>microservice-consumer-order-feign</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <!-- 引入spring boot的依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency> <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency> <!-- feign 依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency> <dependency>
<groupId>com.tuling.cloud</groupId>
<artifactId>microservice-provider-user-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies> <!-- 引入spring cloud的依赖 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <!-- 添加spring-boot的maven插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
ConsumerOrderApplication.java:
package com.jiagoushi.cloud.study; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients; @EnableDiscoveryClient
@SpringBootApplication
// feign 支持
@EnableFeignClients
public class ConsumerOrderApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerOrderApplication.class, args);
}
}
OrderController.java
package com.jiagoushi.cloud.study.user.controller; import com.jiagoushi.cloud.study.user.entity.User;
import com.jiagoushi.cloud.study.user.feign.RefactorUserService;
import com.jiagoushi.cloud.study.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 OrderController { @Autowired
private UserFeignClient userFeignClient; // 为了学习 @GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return userFeignClient.findById2(id);
} @GetMapping("/user-extends/{id}")
public com.jiagoushi.cloud.api.entity.User findById2(@PathVariable Long id) {
return refactorUserService.getUser(id);
} }
UserFeignClient.java
package com.jiagoushi.cloud.study.user.feign; import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import com.jiagoushi.cloud.study.user.entity.User; @FeignClient(name = "microservice-provider-user")
public interface UserFeignClient { @RequestMapping(value = "/{id}", method = RequestMethod.GET) //指名要调用的url
public User findById2(@PathVariable("id") Long id); // 方法名称随便写,但是最好与提供方一样,参数和提供方列表参数的顺序一致
}
欢迎来QQ群:592495675 一起研究 java技术,群里技术大佬,还有所有源代码
springcloud(四) ribbon和feign的更多相关文章
- 一文读懂SpringCloud与Eureka,Feign,Ribbon,Hystrix,Zuul核心组件间的关系
概述 毫无疑问,Spring Cloud是目前微服务架构领域的翘楚,无数的书籍博客都在讲解这个技术.不过大多数讲解还停留在对Spring Cloud功能使用的层面,其底层的很多原理,很多人可能并不知晓 ...
- java框架之SpringCloud(4)-Ribbon&Feign负载均衡
在上一章节已经学习了 Eureka 的使用,SpringCloud 也提供了基于 Eureka 负载均衡的两种方案:Ribbon 和 Feign. Ribbon负载均衡 介绍 SpringCloud ...
- 从实例一步一步入门学习SpringCloud的Eureka、Ribbon、Feign、熔断器、Zuul的简单使用(附代码下载)
场景 SpringCloud -创建统一的依赖管理: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102530574 Sprin ...
- SpringCloud基础概念学习笔记(Eureka、Ribbon、Feign、Zuul)
SpringCloud基础概念学习笔记(Eureka.Ribbon.Feign.Zuul) SpringCloud入门 参考: https://springcloud.cc/spring-cloud- ...
- 小D课堂 - 新版本微服务springcloud+Docker教程_4-06 Feign核心源码解读和服务调用方式ribbon和Feign选择
笔记 6.Feign核心源码解读和服务调用方式ribbon和Feign选择 简介: 讲解Feign核心源码解读和 服务间的调用方式ribbon.feign选择 ...
- springCloud负载均衡Ribbon和Feign的区别
1.什么是负载均衡: 负载均衡(Load Balance)是分布式系统架构设计中必须考虑的因素之一,它通常是指,将请求/数据[均匀]分摊到多个操作单元上执行,负载均衡的关键在于[均匀]. 2.常见的负 ...
- 玩转Spring Cloud之服务注册发现(eureka)及负载均衡消费(ribbon、feign)
如果说用Spring Boot+Spring MVC是开发单体应用(或单体服务)的利器,那么Spring Boot+Spring MVC+Spring Cloud将是开发分布式应用(快速构建微服务)的 ...
- SpringCloud与微服务Ⅶ --- Feign负载均衡
官方文档:https://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign 一.Feign是什么 Feign是一 ...
- SpringCloud(4)---Ribbon服务调用,源码分析
SpringCloud(4)---Ribbon 本篇模拟订单服务调用商品服务,同时商品服务采用集群部署. 注册中心服务端口号7001,订单服务端口号9001,商品集群端口号:8001.8002.800 ...
随机推荐
- Rails-Treasure chest1 (自定义Model网址;多语言包; 时区设置, TimeZone类; 格式日期时间; 表单单选UI; 表单多选UI;Select2 Plugin)
自定义Model网址: 随机值网址SecureRandom.base58 多语言包, 包括默认语言设置和user自设置. 时区设置, TimeZone类 ,增加user自选时区功能 格式日期时间: x ...
- torchnet+VGG16计算patch之间相似度
torchnet+VGG16计算patch之间相似度 torch VGG16 similarity 本来打算使用VGG实现siamese CNN的,但是没想明白怎么使用torchnet对模型进行微调. ...
- Leetcode 35
//在数组最后插入INT_MAX是个好方法class Solution { public: int searchInsert(vector<int>& nums, int targ ...
- Python自动化运维之路-01
python的主要应用 python的擅长领域 学python有没有前途?python的语言排名 语言选择 运维会了开发后可以干什么? python的最大优势就是什么都能做. 课程概述 毕业目标 周五 ...
- BOM之JavaScript常用事件
body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...
- fcntl 改变描述符属性
body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...
- Double H2.0
Double H2.0 https://www.cnblogs.com/wxh9494/p/9879442.html 选题报告 一.项目描述(Project Description) 本项目提供一个公 ...
- 分析hello.java文件
使用JavaServer Faces技术的Web模块示例 1.hello1: hello1应用程序是一个web模块,它使用JavaServer Faces技术来显示问候和响应.可以使用文本编辑器查看应 ...
- JBOSS context root 项目名字默认不写
进到 %JBOSS_HOME%/configuration/standalone.xml,修改下面节点 <virtual-server name="localhost" en ...
- 关于MSSQL中IS NULL和IS NOT NULL的问题
在SQL语句中我们一般会避免写IS NULL和IS NOT NULL,因为这样优化器不会使用索引. 但经过一系列测试发现这句话并不完全对,因为有时候也会使用索引. 语句: select * from ...