springcloud ribbon Finchley 版本,自定义算法
引用上一个项目,在原有的基础上进行更改,添加springcloud的内荣。
eureka-server 和上一个springcloud eureka的一样,没有改动。
添加cloud-api
package com.zhaowb.springcloud.cloudapi.entities; import java.io.Serializable; public class Dept implements Serializable { private Long deptno; // 主键
private String dname; // 部门名称
private String db_source;// 来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库 public Dept() {
} public Dept(String dname) {
super();
this.dname = dname;
} public Long getDeptno() {
return deptno;
} public void setDeptno(Long deptno) {
this.deptno = deptno;
} public String getDname() {
return dname;
} public void setDname(String dname) {
this.dname = dname;
} public String getDb_source() {
return db_source;
} public void setDb_source(String db_source) {
this.db_source = db_source;
} @Override
public String toString() {
return "Dept{" +
"deptno=" + deptno +
", dname='" + dname + '\'' +
", db_source='" + db_source + '\'' +
'}';
}
}
只需要添加这个实体类,在下边使用 。
更改 server-client ,更改为 eureka-hi
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.zhawb.springcloud</groupId>
<artifactId>eureka-hi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>eureka-hi</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>com.example</groupId>
<artifactId>cloud-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.zhaowb.springcloud</groupId>
<artifactId>cloud-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency> <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
配置application.yml
server:
port: 8762
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径
type-aliases-package: com.zhaowb.springcloud.cloudapi.entities # 所有Entity别名类所在包
mapper-locations:
- classpath:/mybatis/mapper/**/*.xml # mapper映射文件 spring:
application:
name: eureka-client-hi
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型
driver-class-name: com.mysql.jdbc.Driver # mysql驱动包
url: jdbc:mysql://localhost:3306/cloudDB01 # 数据库名称
username: root
password: 308539393
dbcp2:
min-idle: 5 # 数据库连接池的最小维持连接数
initial-size: 5 # 初始化连接数
max-total: 5 # 最大连接数
max-wait-millis: 200 # 等待连接获取的最大超时时间 eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
instance:
instance-id: eureka-client-hi
prefer-ip-address: true
info:
app.name: eureka-hi
company.name: www.zhaowb.com
build.artifactId: $project.artifactId$ # 这样写在idea 中运行出来不显示版本号,直接显示 $project.artifactId$ 字符串,可以自己修改
build.version: $project.version$
配置mybatis
目录结构如图:mybatis.cfg.xml ,今开启二级缓存
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings>
<setting name="cacheEnabled" value="true"/><!-- 二级缓存开启 -->
</settings> </configuration>
deptMapper.xml 操作表相关的
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zhawb.springcloud.eurekahi.dao.DeptDao"> <select id="findById" resultType="Dept" parameterType="Long">
select deptno,dname,db_source from dept where deptno=#{deptno};
</select>
<select id="findAll" resultType="Dept">
select deptno,dname,db_source from dept;
</select>
<insert id="addDept" parameterType="Dept">
INSERT INTO dept(dname,db_source) VALUES(#{dname},DATABASE());
</insert> </mapper>
DeptController.java
package com.zhawb.springcloud.eurekahi.controller; import com.zhaowb.springcloud.cloudapi.entities.Dept;
import com.zhawb.springcloud.eurekahi.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*; import java.util.List; @RestController
public class DeptController {
@Autowired
private DeptService service;
@Autowired
private DiscoveryClient client; @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
public boolean add(@RequestBody Dept dept) {
return service.add(dept);
} @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
public Dept get(@PathVariable("id") Long id) {
return service.get(id);
} @RequestMapping(value = "/dept/list", method = RequestMethod.GET)
public List<Dept> list() {
return service.list();
} // @Autowired
// private DiscoveryClient client;
@RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
public Object discovery() {
List<String> list = client.getServices();
System.out.println("**********" + list); List<ServiceInstance> srvList = client.getInstances("MICROSERVICECLOUD-DEPT");
for (ServiceInstance element : srvList) {
System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
+ element.getUri());
}
return this.client;
} }
DeptDao.java
package com.zhawb.springcloud.eurekahi.dao; import com.zhaowb.springcloud.cloudapi.entities.Dept;
import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper
public interface DeptDao { boolean addDept(Dept dept); Dept findById(Long id); List<Dept> findAll();
}
DeptService.java
package com.zhawb.springcloud.eurekahi.service; import com.zhaowb.springcloud.cloudapi.entities.Dept; import java.util.List; public interface DeptService { boolean add(Dept dept); Dept get(Long id); List<Dept> list();
}
DeptServiceImpl.java
package com.zhawb.springcloud.eurekahi.service.impl; import com.zhaowb.springcloud.cloudapi.entities.Dept;
import com.zhawb.springcloud.eurekahi.dao.DeptDao;
import com.zhawb.springcloud.eurekahi.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptDao dao; @Override
public boolean add(Dept dept) {
return dao.addDept(dept);
} @Override
public Dept get(Long id) {
return dao.findById(id);
} @Override
public List<Dept> list() {
return dao.findAll();
} }
启动类EurekaHiApplication.java
package com.zhawb.springcloud.eurekahi; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication
@EnableEurekaClient
public class EurekaHiApplication { public static void main(String[] args) {
SpringApplication.run(EurekaHiApplication.class, args);
}
}
为了使用ribbon的负载均衡,将上面的eureka-hi 复制两份,分别为eureka-hi2,eureka-hi3
server:
port: 8764
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径
type-aliases-package: com.zhaowb.springcloud.cloudapi.entities # 所有Entity别名类所在包
mapper-locations:
- classpath:/mybatis/mapper/**/*.xml # mapper映射文件 spring:
application:
name: eureka-client-hi
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型
driver-class-name: com.mysql.jdbc.Driver # mysql驱动包
url: jdbc:mysql://localhost:3306/cloudDB02 # 数据库名称
username: root
password: 308539393
dbcp2:
min-idle: 5 # 数据库连接池的最小维持连接数
initial-size: 5 # 初始化连接数
max-total: 5 # 最大连接数
max-wait-millis: 200 # 等待连接获取的最大超时时间 eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
instance:
instance-id: eureka-client-hi2
prefer-ip-address: true
info:
app.name: eureka-hi3
company.name: www.zhaowb.com
build.artifactId: $project.artifactId$
build.version: $project.version$
修改端口号,数据库地址,
spring:
application:
name: eureka-client-hi
这个一定不要修改,保持三个一致。
eureka-hi3
server:
port: 8764
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径
type-aliases-package: com.zhaowb.springcloud.cloudapi.entities # 所有Entity别名类所在包
mapper-locations:
- classpath:/mybatis/mapper/**/*.xml # mapper映射文件 spring:
application:
name: eureka-client-hi
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型
driver-class-name: com.mysql.jdbc.Driver # mysql驱动包
url: jdbc:mysql://localhost:3306/cloudDB03 # 数据库名称
username: root
password: 308539393
dbcp2:
min-idle: 5 # 数据库连接池的最小维持连接数
initial-size: 5 # 初始化连接数
max-total: 5 # 最大连接数
max-wait-millis: 200 # 等待连接获取的最大超时时间 eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
instance:
instance-id: eureka-client-hi3
prefer-ip-address: true
info:
app.name: eureka-hi3
company.name: www.zhaowb.com
build.artifactId: $project.artifactId$
build.version: $project.version$
添加一个消费者,cloud-consumer,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.zhaowb.springcloud</groupId>
<artifactId>cloud-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>cloud-consumer</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>com.example</groupId>
<artifactId>cloud-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.zhaowb.springcloud</groupId>
<artifactId>cloud-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
主要是添加,eureka-client 和ribbon的jar
配置 application.yml
server:
port: 8080 eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://localhost:8761/eureka/ spring:
application:
name: cloud-consumer
启动类CloudConsumerApplication.java
package com.zhaowb.springcloud.cloudconsumer; import com.zhaowb.springcloud.cloudconsumer.config.MyRibbonRule;
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.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate; @SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class CloudConsumerApplication { public static void main(String[] args) {
SpringApplication.run(CloudConsumerApplication.class, args);
} @Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
} /**
* 使用ribbon 的随机算法
* @return
*/
// @Bean
// public IRule myrule(){
// return new RandomRule();
// } }
ribbon 默认的是轮询算法,如果想要用随机算法,可以使用下边那个。
DeptConsumerController.java
package com.zhaowb.springcloud.cloudconsumer.controller; import com.zhaowb.springcloud.cloudapi.entities.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import java.util.List; @RestController
public class DeptConsumerController { //eureka-client-hi
private static final String REST_URL_PREFIX = "http://EUREKA-CLIENT-HI"; @Autowired
private RestTemplate restTemplate; @RequestMapping(value = "/consumer/dept/list")
public List<Dept> list() {
return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);
} }
EUREKA-CLIENT-HI 是在eureka server 注册的 application 的名字。
现在就可以在浏览器输入,http://localhost:8080/consumer/dept/list 访问,当看到"db_source":"clouddb02"字段改变,就说明成功了。
自定义ribbon 算法:MyRibbonRule.java 依然是轮训算法,不过更改为了每5次更改一次。
package com.zhaowb.springcloud.cloudconsumer.config; import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server; import java.util.List; public class MyRibbonRule extends AbstractLoadBalancerRule {
// total = 0 // 当total==5以后,我们指针才能往下走,
// index = 0 // 当前对外提供服务的服务器地址,
// total需要重新置为零,但是已经达到过一个5次,我们的index = 1 private int total = 0; // 总共被调用的次数,目前要求每台被调用5次
private int currentIndex = 0; // 当前提供服务的机器号 public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
}
Server server = null; while (server == null) {
if (Thread.interrupted()) {
return null;
}
List<Server> upList = lb.getReachableServers();
List<Server> allList = lb.getAllServers(); int serverCount = allList.size();
if (serverCount == 0) {
/*
* No servers. End regardless of pass, because subsequent passes only get more
* restrictive.
*/
return null;
} // int index = rand.nextInt(serverCount);// java.util.Random().nextInt(3);
// server = upList.get(index); // private int total = 0; // 总共被调用的次数,目前要求每台被调用5次
// private int currentIndex = 0; // 当前提供服务的机器号
if (total < 5) {
server = upList.get(currentIndex);
total++;
} else {
total = 0;
currentIndex++;
if (currentIndex >= upList.size()) {
currentIndex = 0;
}
} if (server == null) {
/*
* The only time this should happen is if the server list were somehow trimmed.
* This is a transient condition. Retry after yielding.
*/
Thread.yield();
continue;
} if (server.isAlive()) {
return (server);
} // Shouldn't actually happen.. but must be transient or a bug.
server = null;
Thread.yield();
}
return server;
} @Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
} @Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
// TODO Auto-generated method stub }
}
在启动类上添加 ,@RibbonClient(value = "EUREKA-CLIENT-HI", configuration = MyRibbonRule.class)
就可以使用自定义算法了,value 是使用在那个微服务上 ,configuration 是自定义的类。
当访问的时候看到刷新5次,db_source"字段 更改一次,说明自定义的算法成功了。
代码在码云上:https://gitee.com/JiShiMoWang/cloud-demo
springcloud ribbon Finchley 版本,自定义算法的更多相关文章
- SpringCloud(Finchley版本)中Zull过滤器ResponseBoby返回中文乱码解决方案
Spring Cloud带有"Cloud"的字样,但它并不是云计算解决方案,而是在Spring Boot基础上构建的,用于快速构建分布式系统的通用模式的工具集.使用Spring C ...
- spring-cloud: eureka之:ribbon负载均衡自定义配置(二)
spring-cloud: eureka之:ribbon负载均衡自定义配置(二) 有默认配置的话基本上就是轮询接口,现在我们改用自定义配置,同时支持:轮询,随机接口读取 准备工作: 1.eureka服 ...
- SpringCloud 教程 | 第一篇: 服务的注册与发现Eureka(Finchley版本)
一.spring cloud简介 鉴于<史上最简单的Spring Cloud教程>很受读者欢迎,再次我特意升级了一下版本,目前支持的版本为Spring Boot版本2.0.3.RELEAS ...
- 史上最简单的 SpringCloud 教程 | 第一篇: 服务的注册与发现Eureka(Finchley版本)
转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springcloud/2018/08/30/sc-f1-eureka/ 本文出自方志朋的博客 一.spring ...
- SpringCloud教程二:Ribbon(Finchley版)
在上一篇文章,讲了服务的注册和发现.在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的.Spring cloud有两种服务调用方式,一种是ribbon+r ...
- SpringCloud学习(一)服务的注册与发现Eureka(Finchley版本)
创建服务注册中心 在这里,我还是采用Eureka作为服务注册与发现的组件. 首先创建一个空项目 首先创建一个空项目,再创建一个maven项目,首先创建一个主Maven工程,在其pom文件引入依赖,sp ...
- SpringCloud教程 | 第六篇: 分布式配置中心(Spring Cloud Config)(Finchley版本)
在上一篇文章讲述zuul的时候,已经提到过,使用配置服务来保存各个服务的配置文件.它就是Spring Cloud Config. 一.简介 在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管 ...
- springcloud Eureka Finchley.RELEASE 版本
创建一个父项目cloud-demo pom.xml <?xml version="1.0" encoding="UTF-8"?> <proje ...
- 客户端实现负载均衡:springCloud Ribbon的使用
Netfilx发布的负载均衡器,是一个基于http.tcp的客户端负载均衡工具,具有控制http.tcp客户端的行为,为ribbon配置服务提供者的地址后,ribbon就 可以经过springClou ...
随机推荐
- 云栖干货回顾 | 云原生数据库POLARDB专场“硬核”解析
POLARDB是阿里巴巴自主研发的云原生关系型数据库,目前兼容三种数据库引擎:MySQL.PostgreSQL.Oracle.POLARDB的计算能力最高可扩展至1000核以上,存储容量可达100TB ...
- lua数据类型与变量
Lua数据类型与变量 Lua中有 8个基本类型分别为: nil.boolean.number.string.userdata.function.thread和 table. lua变量三种类型:全局 ...
- NX二次开发-NXOPEN将工程图转成PDF文件
NX9+VS2012 #include <uf.h> #include <uf_draw.h> #include <NXOpen/PrintPDFBuilder.hxx& ...
- class8_Canvas 画布
最终的部分运行效果图(程序见序号4): #!/usr/bin/env python# -*- coding:utf-8 -*-# ----------------------------------- ...
- IntelliJ IDEA 创建的文件自动生成 Author 注释 签名
IntelliJ IDEA 创建的文件自动生成 Author 注释 签名1.打开 File --> Setting2.找到 Editor --> File and Code Templat ...
- C盘清理垃圾
经常清理C盘垃圾,会让系统运行更快,避免死机,今天教大家一种简单实用的方法,用文本文档清理垃圾: 1:在电脑桌面空白处右键-建立文本文档: 2:把以下代码复制到文本里 @echo offecho 正在 ...
- 《转》python学习基础
学习的python本来想自己总结,但是发现了一篇不错的大牛的博客,拿来主义,,又被我实践了 关于前两篇如果总结的不详细,因此把他人的转载过来 http://www.cnblogs.com/BeginM ...
- Codeforces 479【D】div3
题目链接:http://codeforces.com/problemset/problem/977/D 题意:给你一个数字序列,定了一个游戏规则.你可以对当前数字进行两个操作 1./ 3 如果这个数 ...
- The linux command 之引用
[me@linuxbox ~]$ echo this is a test this is a test shell 会对echo进行单词分割(word splitting)去除多余的空白. [me@l ...
- FCC——相关练习
算法题目1:Seek and Destroy(摧毁数组) 金克斯的迫击炮! 实现一个摧毁(destroyer)函数,第一个参数是待摧毁的数组,其余的参数是待摧毁的值. 帮助资源: Arguments ...