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 ...
随机推荐
- 单例模式(Singleton-Pattern)百媚生
1 动机 对于系统中的某些类来说,只有一个实例很重要,例如,一个系统中可以存在多个打印任务,但是只能有一个正在工作的任务;一个系统只能有一个窗口管理器或文件系统;一个系统只能有一个计时工具或ID(序号 ...
- jar插件应用
Gson(解析json) 作用:在servlet层中解析json 1:导入jar包 gson-2.2.4.jar 例如:Gson gson = new Gson(); ...
- 使用触发器定义 WPF 控件的行为
Expression Studio 4.0 其他版本 Expression Studio 3.0 Expression Studio 2.0 此主题尚未评级 - 评价此主题 在应用程序的生 ...
- link @import区别 src href的区别
先说页面引入css的四种方式吧 1 在头部写在style里面 2 行内样式 tyle= 3 外部引入 link和@import的区别 link属于XHTML的标签,而@import只是css提供的一种 ...
- PHP:第五章——字符串过滤函数
<?php header("Content-Type:text/html;charset=utf-8"); //字符串过滤函数: //1.n12br 在所有新行之前插入Htm ...
- 使用peach工具进行fuzz测试
本文简要介绍了Fuzz 工具Peach的使用,并通过文件格式 Fuzz举例阐述了 Peach Pit 文件的编写. 本文转自“绿盟科技博客”:http://blog.nsfocus.net/peach ...
- bug 报告
准备工作:首先我下载了Git Bash这个软件,利用了老师所给的git命令,批量的pull所有同学第二次作业的代码.截图如下: 一.被测试程序的作者:方铭 程序git地址:https://coding ...
- springboot项目配置拦截器,进行登陆等拦截
新建拦截类: public class LoginInterceptor implements HandlerInterceptor{ private static Log logger = LogF ...
- CH1808 Milking Grid
题意 POJ2185 数据加强版 描述 Every morning when they are milked, the Farmer John's cows form a rectangular gr ...
- Pandas Timestamp 和 python 中 datetime 的互相转换
Pandas 的Timestamp 和 python 的 datetime, 这是两种不同的类型. 它们之间可以互相转换. refer to: https://www.jianshu.com/p/ ...