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 ...
随机推荐
- 【Python】使用Pytest集成Allure生成漂亮的图形测试报告
前言 大概两个月前写过一篇<[测试设计]使用jenkins 插件Allure生成漂亮的自动化测试报告>的博客,但是其实Allure首先是一个可以独立运行的测试报告生成框架,然后才有了Jen ...
- TinyURL
2018-03-09 15:19:04 TinyURL,短地址,或者叫短链接,指的是一种互联网上的技术与服务.此服务可以提供一个非常短小的URL以代替原来的可能较长的URL,将长的URL地址缩短. 用 ...
- JAVA异常处理机制分析(上)
过去曾有一段时间关于java的异常处理机制曾经让我吃尽苦头,异常机制看似简单,原理,用法也仅仅如此,但是,用起来或是在使用一些框架的时候总会因为使用不当,造成灾难性后果. jdk异常处理机制 ...
- 利用JS将页面中包含“一个”字段值的元素改为红色
document.body.innerHTML = document.body.innerHTML.replace(/一个/ig,"<span style='color: red;'& ...
- HDU 5816 状压DP&排列组合
---恢复内容开始--- Hearthstone Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java ...
- 前端工程构建工具——Yeoman
一.Yeoman 简介 通常在开发新项目时我们都需要配置工程环境,开发目录,需要下载一些库.框架文件(如 jQuery.Backbone 等),配置编译环境(Less.Sass.Coffeescrip ...
- 网络流量预测 国内外研究现状【见评论】——传统的ARIMA、HMM模型,目前LSTM、GRU、CNN应用较多,貌似小波平滑预处理步骤非常关键
Time Series Anomaly Detection in Network Traffic: A Use Case for Deep Neural Networks from:https://j ...
- 019PHP基础知识——函数(二)
<?php /** * 变量的作用范围 * 函数体内的变量只作用于函数体内. */ /*$bbs="bbs.blog.com"; function say(){ $bbs=& ...
- jQuery 参数详解
url: 要求为String类型的参数,发送请求的地址.如果没有填写, 默认发送当前页的url type: 要求为String类型的参数,请求方式(post或get)默认为get. 注意其他http请 ...
- node 使用范围 和 node的优势 (为什么 创业公司 选择的不是 java php ruby 等)
链接 一些国外大公司 范围: 第一: 希望合并后台多个接口 成为一个接口, 或者频繁改动接口 相关, 比如数据 和数据格式之类, 后台难以配合, 这里可以使用node作为后台的应用层调用其他接口 ...