SpringCloud2.x搭建完整Demo(三) -集成Ribbon负载均衡,Feign接口服务
1.集成Ribbon负载均衡(实现负载均衡,全局Ribbon路由配置,提供服务提供方信息)
2.集成Feign接口服务
---------------------------------------------------------------------------------------------------------------------------
1.1 在消费者服务集成Ribbon,修改POM,增加Eureka支持
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
1.2 修改RestConfig配置类,在获取RestTemplate对象的时候加入Ribbon的配置信息
1.3 消费者服务application.yml配置文件增加Eureka配置
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://admin:root@eureka:7001/eureka,http://admin:root@eureka2:7002/eureka,http://admin:root@eureka3:7003/eureka
1.4 消费者服务启动类增加注解
1.5 消费者服务Controller修改请求地址
private static final String PRODUCT_GET_URL = "http://MYSPRINGCLOUD-PROVIDER-PRODUCT/prodcut/getInfoById/";
private static final String PRODUCT_LIST_URL="http://MYSPRINGCLOUD-PROVIDER-PRODUCT/prodcut/getAllInfo/";
private static final String PRODUCT_ADD_URL = "http://MYSPRINGCLOUD-PROVIDER-PRODUCT/prodcut/addInfo/";
1.6 为了体现出负载均衡的效果,复制两个产品服务,在复制两个库
server:
port: 8082
mybatis:
mapper-locations: # 所有的mapper映射文件
- classpath:mapping/*.xml
spring:
application:
name: myspringcloud-provider-product
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 配置当前要使用的数据源的操作类型
driver-class-name: com.mysql.cj.jdbc.Driver # 配置MySQL的驱动程序类
url: jdbc:mysql://localhost:3306/springcloud2?serverTimezone=GMT%2B8 # 数据库连接地址
username: root
password: root
logging:
level:
com.en.mapper: debug
eureka:
client: # 客户端进行Eureka注册的配置
service-url:
defaultZone: http://admin:root@eureka:7001/eureka,http://admin:root@eureka2:7002/eureka,http://admin:root@eureka3:7003/eureka
instance:
instance-id: myspringcloud-provider-product2
prefer-ip-address: true
lease-renewal-interval-in-seconds: 2 # 设置心跳的时间间隔(默认是30秒)
lease-expiration-duration-in-seconds: 5 # 如果现在超过了5秒的间隔(默认是90秒)
info:
app.name: myspringcloud-provider-product2
company.name: en
build.artifactId: $project.artifactId$
build.modelVersion: $project.modelVersion$
server:
port: 8083
mybatis:
mapper-locations: # 所有的mapper映射文件
- classpath:mapping/*.xml
spring:
application:
name: myspringcloud-provider-product
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 配置当前要使用的数据源的操作类型
driver-class-name: com.mysql.cj.jdbc.Driver # 配置MySQL的驱动程序类
url: jdbc:mysql://localhost:3306/springcloud3?serverTimezone=GMT%2B8 # 数据库连接地址
username: root
password: root
logging:
level:
com.en.mapper: debug
eureka:
client: # 客户端进行Eureka注册的配置
service-url:
defaultZone: http://admin:root@eureka:7001/eureka,http://admin:root@eureka2:7002/eureka,http://admin:root@eureka3:7003/eureka
instance:
instance-id: myspringcloud-provider-product3
prefer-ip-address: true
lease-renewal-interval-in-seconds: 2 # 设置心跳的时间间隔(默认是30秒)
lease-expiration-duration-in-seconds: 5 # 如果现在超过了5秒的间隔(默认是90秒)
info:
app.name: myspringcloud-provider-product3
company.name: en
build.artifactId: $project.artifactId$
build.modelVersion: $project.modelVersion$
CREATE DATABASE springcloud2 CHARACTER SET UTF8 ;
USE springcloud2;
CREATE TABLE product (
productId BIGINT AUTO_INCREMENT ,
productName VARCHAR(50) ,
productDesc VARCHAR(50) ,
CONSTRAINT pk_prodcut_id PRIMARY KEY(productId)
) ;
INSERT INTO product(productName,productDesc) VALUES ('java编程',DATABASE()) ;
INSERT INTO product(productName,productDesc) VALUES ('C',DATABASE()) ;
INSERT INTO product(productName,productDesc) VALUES ('C++',DATABASE()) ;
INSERT INTO product(productName,productDesc) VALUES ('Springboot',DATABASE()) ;
INSERT INTO product(productName,productDesc) VALUES ('springcloud',DATABASE()) ;
CREATE DATABASE springcloud3 CHARACTER SET UTF8 ;
USE springcloud3;
CREATE TABLE product (
productId BIGINT AUTO_INCREMENT ,
productName VARCHAR(50) ,
productDesc VARCHAR(50) ,
CONSTRAINT pk_prodcut_id PRIMARY KEY(productId)
) ;
INSERT INTO product(productName,productDesc) VALUES ('java编程',DATABASE()) ;
INSERT INTO product(productName,productDesc) VALUES ('C',DATABASE()) ;
INSERT INTO product(productName,productDesc) VALUES ('C++',DATABASE()) ;
INSERT INTO product(productName,productDesc) VALUES ('Springboot',DATABASE()) ;
INSERT INTO product(productName,productDesc) VALUES ('springcloud',DATABASE()) ;
1.7 启动服务,浏览器消费者服务多次调用接口,可以看到Ribbon负载均衡生效,默认轮询策略。
1.8 消费者服务配置类新增全局配置,负载均衡改为随机策略
@Bean
public IRule ribbonRule() {
return new com.netflix.loadbalancer.RandomRule();
}
1.9 服务消费方获取服务提供方信息,修改ConsumerProductController.java
@Resource
private LoadBalancerClient loadBalancerClient;
@RequestMapping("/product/getAllInfo")
public Object listProduct() {
ServiceInstance serviceInstance = this.loadBalancerClient.choose("MYSPRINGCLOUD-PROVIDER-PRODUCT") ;
System.out.println(
"【*** ServiceInstance ***】host = " + serviceInstance.getHost()
+ "、port = " + serviceInstance.getPort()
+ "、serviceId = " + serviceInstance.getServiceId());
return restTemplate.exchange(PRODUCT_LIST_URL,HttpMethod.GET,new HttpEntity<>(httpHeaders), List.class).getBody();
}
2.1 复制myspringcloud-consumer 成一个新的模块myspringcloud-consumer-feign,修改POM
org.springframework.cloud
spring-cloud-starter-openfeign
2.2 新建立一个myspringcloud-service模块,专门定义客户端的调用接口,修改POM
myspringcloud
com.en
1.0-SNAPSHOT
4.0.0
myspringcloud-service
UTF-8
org.springframework.cloud
spring-cloud-starter-openfeign
com.en
myspringcloud-api
2.3 在myspringcloud-service新建com.en.config路径,新建FeignClientConfig配置类
package com.en.feign;
import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignClientConfig {
@Bean
public BasicAuthRequestInterceptor getBasicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("admin", "root");
}
}
2.4 myspringcloud-service 模块新建IProductClientService接口
package com.en.service;
import com.en.feign.FeignClientConfig;
import com.en.po.ProductPo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@FeignClient(name = "MYSPRINGCLOUD-PROVIDER-PRODUCT",configuration = FeignClientConfig.class)
public interface IProductClientService {
@RequestMapping("/prodcut/getInfoById/{id}")
ProductPo getProduct(@PathVariable("id")long id);
@RequestMapping("/prodcut/getAllInfo")
List listProduct() ;
@RequestMapping("/prodcut/addInfo")
boolean addPorduct(ProductPo productPo) ;
}
2.5 myspringcloud-consumer-feign 修改pom文件,引入myspringcloud-service 依赖
com.en
myspringcloud-service
1.0-SNAPSHOT
compile
2.6 myspringcloud-consumer-feign模块删除RestConfig配置类,并修改ConsumerProductController
package com.en.controller;
import com.en.po.ProductPo;
import com.en.service.IProductClientService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @ClassName ConsumerProductController
* @Description 服务消费方控制器
* @Author liuxiaobai
* @Date 2020年6月26日09:18:41
* @Version 1.0
**/
@RestController
@RequestMapping("/consumer")
public class ConsumerProductController {
@Resource
private IProductClientService iProductClientService;
@RequestMapping("/product/getInfoById")
public Object getProduct(long id) {
return iProductClientService.getProduct(id);
}
@RequestMapping("/product/getAllInfo")
public Object listProduct() {
return iProductClientService.listProduct();
}
@RequestMapping("/product/addInfo")
public Object addPorduct(ProductPo productPo) {
return iProductClientService.addPorduct(productPo);
}
}
2.7 myspringcloud-consumer-feign模块修改程序启动类,新增@EnableFeignClients注解
package com.en;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients("com.en.service")
public class ConsumerApplicationFeign {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplicationFeign.class,args);
}
}
2.8 启动服务测试接口调用正常,并自带负载均衡
源码自取:
github地址:https://github.com/L1021204735/myspringcloud3