当前位置: 首页 > 编程日记 > 正文

SpringCloud + Consul服务注册中心 + gateway网关

1  启动Consul

2  创建springcloud-consul项目及三个子模块

2.1 数据模块consul-producer

2.2 数据消费模块consul-consumer

2.3 gateway网关模块

3  测试及项目下载

1、首先安装Consul并启动Consul,端口号为8500

2、创建一个maven项目springcloud-consul,修改pom.xml添加SpringBoot及SpringCloud依赖(这里展示的是最后的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.test</groupId><artifactId>springcloud-consul</artifactId><packaging>pom</packaging><version>1.0-SNAPSHOT</version><modules><module>consul-producer</module><module>consul-consumer</module><module>gateway-service</module></modules><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.4.RELEASE</version><relativePath/></parent><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><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><spring-cloud.version>Finchley.RELEASE</spring-cloud.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-discovery</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-config</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

2.1  数据提供模块consul-producer

创建数据提供服务模块consul-producer,修改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"><parent><artifactId>springcloud-consul</artifactId><groupId>com.test</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>consul-producer</artifactId><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>4.3.1</version></dependency></dependencies></project>

配置文件application.yml文件为:

debug: falsespring.aop.auto: truespring:application:name: data-producercloud:consul:enabled: truehost: localhostport: 8500discovery:enabled: trueregister: true    #是否将自身服务注册到consul中hostname: 127.0.0.1healthCheckPath: /actuator/health  #服务健康检查地址healthCheckInterval: 15sserviceName: ${spring.application.name}tags: testinstanceId: ${spring.application.name}-${spring.cloud.client.ip-address}-${server.port}  # 服务id

启动类DataProducerApplication

package com.test;import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.NetUtil;
import cn.hutool.core.util.NumberUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;@EnableDiscoveryClient
@SpringBootApplication
@EnableAutoConfiguration
public class DataProducerApplication {public static void main(String[] args) {int port = 0;int defaultPort = 8080;int time = 5;Future<Integer> future = ThreadUtil.execAsync(() ->{int p = defaultPort;System.out.println(String.format("请于%d秒钟内输入端口号, 推荐  8080 、 8081  或者  8082,超过%d秒将默认使用 %d", time, time, defaultPort));Scanner scanner = new Scanner(System.in);while(true) {String strPort = scanner.nextLine();if(!NumberUtil.isInteger(strPort)) {System.err.println("只能是数字");} else {p = Convert.toInt(strPort);scanner.close();break;}}return p;});try{port=future.get(time, TimeUnit.SECONDS);}catch (InterruptedException | ExecutionException | TimeoutException e){port = defaultPort;}if(!NetUtil.isUsableLocalPort(port)) {System.err.printf("端口%d被占用了,无法启动%n", port );System.exit(1);}new SpringApplicationBuilder(DataProducerApplication.class).properties("server.port=" + port).run(args);}
}

DataController处理每一个请求

package com.test.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;@RestController
public class DataController {@RequestMapping("/*")public String get(HttpServletRequest request) {return String.format("实际响应地址:%s", request.getRequestURL().toString());}
}

2.2  数据消费模块consul-consumer

使用LoadBalancerClient实现服务转发,即将服务映射到consul-producer服务

修改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"><parent><artifactId>springcloud-consul</artifactId><groupId>com.test</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>consul-consumer</artifactId><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies></project>

配置文件application.yml

spring:application:name: data-consumercloud:consul:host: 127.0.0.1port: 8500discovery:register: truehostname: 127.0.0.1healthCheckPath: /actuator/health
server:port: 8090data-producer: data-producer

启动类DataConsumerApplication

package com.test;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication
@EnableDiscoveryClient
public class DataConsumerApplication {public static void main(String[] args) {SpringApplication.run(DataConsumerApplication.class, args);}
}

DataConsumerController处理请求

package com.test.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;import javax.servlet.http.HttpServletRequest;@RestController
public class DataConsumerController {@Value("${data-producer}")private String dataProducer;@Autowiredprivate LoadBalancerClient loadBalancerClient;@RequestMapping("/data-api/**")public String test(HttpServletRequest request) {ServiceInstance serviceInstance = loadBalancerClient.choose(dataProducer);String result = new RestTemplate().getForObject(serviceInstance.getUri().toString() + request.getRequestURI().replace("data-api", ""),String.class);System.out.println(result);return result;}
}

2.3 gateway网关实现服务转发

创建gateway-service模块,修改pom.xml增加gateway所需依赖

<?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"><parent><artifactId>springcloud-consul</artifactId><groupId>com.test</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>gateway-service</artifactId><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency></dependencies></project>

配置文件application.yml

server:port: 8100spring:application:name: gateway-servicecloud:gateway:routes:- id: data-service1  #请求 http://localhost:8100/data-service1/test会转发到data-producer服务,uri: lb://data-producer  #在服务注册中心找服务名为 data-producer的服务,
          predicates:- Path=/data-service1/*filters:- StripPrefix=1- id: data-service2  # 请求 http://localhost:8100/data-service2/test转发到 http://localhost:8080/testuri: http://localhost:8080predicates:- Path=/data-service2/*filters:- StripPrefix=1  #前缀, 在当前路径匹配中表示去掉第一个前缀 /data-service2consul:enabled: truehost: localhostport: 8500discovery:enabled: trueregister: false    #是否将自身服务注册到consul中hostname: 127.0.0.1healthCheckPath: /actuator/health  #服务健康检查地址healthCheckInterval: 15sserviceName: ${spring.application.name}tags: testinstanceId: ${spring.application.name}-${spring.cloud.client.ip-address}-${server.port}  # 服务id

启动类GatewayServiceApplication

package com.test;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication
public class GatewayServiceApplication {public static void main(String[] args) {SpringApplication.run(GatewayServiceApplication.class, args);}
}

3、测试及项目下载

首先启动consul,启动两个DataProducerApplication实例,端口号为8080、8081, 启动DataConsumerApplication及GatewayServiceApplication

DataConsumerApplication服务

在浏览器输入http://localhost:8090/data-api/test, 访问DataConsumerApplication服务,输出结果为: “实际响应地址:http://127.0.0.1:8081/test”  或  "实际响应地址:http://127.0.0.1:8080/test"

GatewayServiceApplication服务

转发格式见application.yml文件

在浏览器中输入http://localhost:8100/data-service1/test, 访问GatewayServiceApplication同样 可以看到  有时访问8080端口的DataProducerApplication服务,有时访问8081端口的DataProducerApplication服务

在浏览器中输入http://localhost:8100/data-service2/test, 实际响应的是8080端口的DataProducerApplication服务,

项目下载

转载于:https://www.cnblogs.com/wushengwuxi/p/11585567.html

相关文章:

MySql按日期进行统计(前一天、本周、某一天)[转载]

转自&#xff1a;http://www.yovisun.me/mysql-date-statistics.html 在mysql数据库中&#xff0c;常常会遇到统计当天的内容。例如&#xff0c;在user表中&#xff0c;日期字段为&#xff1a;log_time 统计当天 sql语句为&#xff1a; select * from user where date(log_time…

右键新建里面没有word和excel_Windows10系统下如何将Sublime Text3添加到右键快捷菜单?...

由于本人用的Sublime Text是汉化绿色版的&#xff0c;不仅仅是因为绿色版免去了安装步骤 解压即用&#xff0c;还因为里面整合了常用的高效率必备插件&#xff0c;但是发现右键竟然没有用Sublime Text打开的快捷菜单&#xff0c;这对于我使用Sublime Text 打开一些代码文档会有…

NOI2011 道路修建

题目连接&#xff1a;http://221.192.240.123:8586/JudgeOnline/showproblem?problem_id1670 题意自便。 相关知识&#xff1a;树的遍历&#xff0c;非递归DFS写法。 分析&#xff1a;因为树的边给定&#xff0c;所以从哪个点开始求都是一样的。递归求出每个点的的子树个数&am…

Wiener Filter

假设分别有两个WSS process&#xff1a;$x[n]$&#xff0c;$y[n]$&#xff0c;这两个process之间存在某种关系&#xff0c;并且我们也了解这种关系。现在我们手头上有process $x[n]$&#xff0c;目的是要设计一个LTI系统&#xff0c;使得系统输出$y[n]$&#xff0c;不过$y[n]$是…

c++ string replace_JAVA应用程序开发之String类常用API

【本文详细介绍了JAVA应用开发中的String类常用API&#xff0c;欢迎读者朋友们阅读、转发和收藏&#xff01;】1 基本概念API ( Application Interface 应用程序接口)是类中提供的接口&#xff0c;类库是类的集合。在 Java 语言中可以通过 import 关键字导入相关的类&#xff0…

强大的Charles的使用,强大的flutter1.9

<a href"http://www.cocoachina.com/articles/37551?filterios"> 强大的Charles强大的flutter转载于:https://www.cnblogs.com/henusyj-1314/p/11586350.html

多层次架构设计前言

因为 php 原生来就是要辅助 HTML 的产生&#xff0c;所以程式码跟 HTML 码混在一起写&#xff0c;正是 PHP 的特点也是优点&#xff0c;但正也造成很多分工上的问题&#xff0c;也就是你在写 php 的同时&#xff0c;你也必须很了解 前端、后端技能&#xff0c;像是 DataBase, H…

在java的程序里date类型比较大小

Date a; Date b; 假设现在你已经实例化了a和b a.after(b)返回一个boolean&#xff0c;如果a的时间在b之后&#xff08;不包括等于&#xff09;返回trueb.before(a)返回一个boolean&#xff0c;如果b的时间在a之前&#xff08;不包括等于&#xff09;返回truea.equals(b)返回一个…

linux安装ActiveMQ

1. 下载&#xff1a; # wget https://archive.apache.org/dist/activemq/5.14.0/apache-activemq-5.14.0-bin.tar.gz 2. 解压&#xff1a; # tar zxvf apache-activemq-5.14.0-bin.tar.gz -C ../ 3. 配置环境变量&#xff1a; # vim /etc/profile 4. 启动&#xff1a; # active…

用递归来判断输入的字符串是否是回文

设计思路&#xff1a;导入Scanner类输入字符串&#xff0c;再将输入的字符串转化为字符数组&#xff0c;然后从字符串左右两侧依次比较字符chu是否相同&#xff0c;若相同递归返回读取的字符个数&#xff0c;若返回字符的个数输入字符串的长度&#xff0c;则输出该字符串是回文…

js高级程序设计之跨浏览器事件处理

//事件 var EventUtil { //添加事件 addHandler:function (element, type, handler) { //element:DOM对象,type:事件类型,handler:事件函数 if (element.addEventListener) { //是否存在DOM2级方法 element.addEventListener(type, handler, false); } else if (element.attac…

在python中使用关键字define定义函数_python自定义函数def的应用详解

这里是三岁&#xff0c;来和大家唠唠自定义函数&#xff0c;这一个神奇的东西&#xff0c;带大家白话玩转自定义函数 自定义函数&#xff0c;编程里面的精髓&#xff01; def 自定义函数的必要函数&#xff1a;def 使用方法&#xff1a;def 函数名(参数1&#xff0c;参数2&…

在Win7 + VMware7下安装Xcode 4

我的Mac OS X是在Win7下虚拟机上安装的&#xff0c;我先把xcode_4.0.2_and_ios_sdk_4.3.dmg下载到Win7下某个目录下&#xff0c;然后共享该目录&#xff0c;然后启动Mac OS X&#xff0c;开始安装&#xff1a;1. 找到Win7下xcode_4.0.2_and_ios_sdk_4.3.dmg所在的共享文件夹&am…

plsql误删除数据,提交事务后如何找回?

select *from tbs_rep_template as of timestamp to_timestamp(2018-07-12 14:23:00, yyyy-mm-dd hh24:mi:ss)where tplname like %工业管道定期检验报告%;--其中2018-07-12 14:23:00为:误删数据的大致时刻的提前时间转载于:https://www.cnblogs.com/demon09/p/9300756.html

配置flutter For IOS

https://www.cnblogs.com/lovestarfish/p/10628205.html第一步&#xff0c;下载flutter最新版&#xff0c;解压到自己的目录里&#xff1a; 提供网址&#xff1a;https://flutter.io/setup-macos/ 第二步&#xff0c;终端配置环境&#xff0c;这里我配知道了IOS&#xff0c;安…

Unity3D 镜面反射

原创文章如需转载请注明&#xff1a;转载自 脱莫柔Unity3D学习之旅 QQ群&#xff1a;【119706192】 本文链接地址: Unity3D 镜面反射 这是官方CharacterCustomization事例中的镜面反射shader。 1.首先需要一个plane当镜子&#xff0c;将代码MirrorReflection.cs文件绑定到镜子…

python后端学什么框架_献给正在学习python的你, 10个最受欢迎的Python开源框架

很多小伙伴在学习wen的时候说&#xff0c;有没有几个常用的框架&#xff0c;好多小伙伴都只说对了其中几个&#xff0c;只有少部分是说正确的&#xff0c;想要了解更多&#xff0c;欢迎大家订阅微信公众号&#xff1a;Python从程序猿到程序员&#xff0c;或者加4913.08659&…

HubbleDotNet 简介 (转)

系统简介 HubbleDotNet 是一个基于.net framework 的开源免费的全文搜索数据库组件。开源协议是 Apache 2.0。HubbleDotNet提供了基于SQL的全文检索接口&#xff0c;使用者只需会操作SQL&#xff0c;就可以很快学会使用HubbleDotNet进行全文检索。 HubbleDotNet可以实现全文索引…

JavaScript夯实基础系列(四):原型

在JavaScript中有六种数据类型&#xff1a;number、string、boolean、null、undefined以及对象&#xff0c;ES6加入了一种新的数据类型symbol。其中对象称为引用类型&#xff0c;其他数据类型称为基础类型。在面向对象编程的语言中&#xff0c;对象一般是由类实例化出来的&…

python中意外缩进是什么意思_Python 的缩进是不是反人类的设计?

前些天&#xff0c;我写了《Python为什么使用缩进来划分代码块&#xff1f;》&#xff0c;文中详细梳理了 Python 采用缩进语法的 8 大原因。我极其喜欢这种简洁优雅的风格&#xff0c;所以对它赞美有加。 然而文章发出去后&#xff0c;非常意外&#xff0c;竟收到了大量的反对…

netstat命令

使用netstat -nap可以查看当前发送和接收队列&#xff0c;Send-Q 很高时表示发送队列太长&#xff0c;可能网络阻塞 转载于:https://www.cnblogs.com/wx170119/p/11606909.html

mysql操作数字名称的schema时字符的逃逸问题

一个简单的问题折腾了好大一会儿&#xff0c;mysql不支持直接操作数字名称的schema&#xff0c;在sql操作时必须做字符逃逸&#xff0c;如&#xff1a; char sql_str[1000]; memset(sql_str, 0x0, 1000); sprintf(sql_str, "CREATE TABLE IF NOT EXIST %s.%s(data_id INT(…

使用XMLSpyDocEditPlugIn2.dll,页面加载失败

维护项目中遇到问题&#xff0c;项目用到XMLSpyDocEditPlugIn2.dll的acticex控件&#xff0c;客户换了其他pc后&#xff0c;不能下载安装acticex控件&#xff0c;所以不能使用此功能。解决方法&#xff1a; 1 下载 XMLSpyDocEditPlugIn2.dll&#xff0c; 路径 http://download.…

[bzoj4562][Haoi2016]食物链_记忆化搜索_动态规划

食物链 bzoj-4562 Haoi-2016 题目大意&#xff1a;给你n个点&#xff0c;m条边的DAG&#xff0c;求所有的满足条件的链&#xff0c;使得每条链的起点是一个入度为0的点&#xff0c;中点是一条出度为0的点。 注释&#xff1a;$1\le n\le 10^5$&#xff0c;$1\le m\le 2*10^5$。 …

Apache源码包在LINUX(CENTOS6.8)中的安装(出现问题及解决)

任务&#xff1a;在CENT6.8系统中安装Apache&#xff08;版本为&#xff1a;httpd-2.4.41&#xff09; 前提&#xff1a;由于源码包必须先编译后安装&#xff0c;所以必须先安装编译器&#xff1a;gcc 理论步骤&#xff1a; 1.检测gcc软件包&#xff0c;如果不存在则进行安装。…

append函数_连载|想用Python做自动化测试?函数的参数传递机制及变量作用域

“ 这一节有点难。看不懂没关系。继续往后学&#xff0c;回头再来看。”10.6 函数参数传递的机制10.6.1 值传递与引用传递编程语言的参数传递机制通常有两种&#xff1a;值传递拷贝参数的值&#xff0c;然后传递给函数里的新变量。这样&#xff0c;原变量和新变量之间互相独立&…

PowerDesigner生成数据库

此文中图片不小心被删除了&#xff0c;特重写了PowerDesigner生成数据库修改 一、 用POWERDESIGNER生成数据库 FILE&#xff0d;》NEW 在MODEL NAME中输入模版名 在DBMS中选择要连接的数据库类型 点击确定 确定后出现如下页面 选中工具条面版上的 表按钮 在…

随想_8_Windows_XP_Explorer_错误

最近发现微软的系统的稳定性&#xff0c;还是有待提高啊&#xff0c;这不XP SP3的资源管理器&#xff0c;就犯毛病了&#xff0c;俗话说有图 有真相&#xff0c;各位请看&#xff1a; 大家看&#xff0c;资源管理器左边的导航栏&#xff0c; 就可以发现&#xff0c;里面很多东西…

webpack笔记(6)调试模式

在配置devtool时&#xff0c;webpack给我们提供了四种选项。 source-map:在一个单独文件中产生一个完整且功能完全的文件。这个文件具有最好的source map,但是它会减慢打包速度&#xff1b;cheap-module-source-map:在一个单独的文件中产生一个不带列映射的map&#xff0c;不带…

nicstat命令安装与分析

nicstat安装包下载与安装&#xff1a; wget https://downloads.sourceforge.net/project/nicstat/nicstat-1.95.tar.gz tar -zxvf nicstat-1.95.tar.gz cd nicstat-1.95 cp Makefile.Linux Makefile vi Makefile 后修改 CFLAGS $(COPT) make && make install //…