springcloud 配置中心与zuul反向代理

统一配置中心概述

如果微服务架构中没有使用统一配置中心时,所存在的问题:

  • 配置文件分散在各个项目里,不方便维护

  • 配置内容安全与权限,实际开发中,开发人员是不知道线上环境的配置的

  • 更新配置后,项目需要重启


    在SpringCloud中我们使用config组件来作为统一配置中心:
    在这里插入图片描述
    废话不多说,本小节我们来开发统一配置中心的server端:

    先在你的项目里加一个模块:
    在这里插入图片描述
    项目的pom.xml文件配置的依赖如下:

<dependencies>
	<!-- 配置中心 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
</dependencies>

        增加一个Main方法 ConfigMain.java:

@SpringBootApplication
@EnableConfigServer // 激活该应用为配置文件服务器:读取远程配置文件,转换为rest接口服务
public class ConfigMain {
    public static void main(String[] args) {
        new SpringApplicationBuilder(ConfigMain.class).web(true).run(args);
    }
}

增加 application.yml 资源文件:

server:
  port: 8040
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/wufewu/userservice  # 配置git仓库的地址

在这里插入图片描述
在这里插入图片描述

运行Main方法,然后去浏览器上查看资源文件:
访问网址:http://localhost:8040/userservice/dev
访问网址:http://localhost:8040/userservice-dev.yml
在这里插入图片描述
微服务项目:


将微服务的application.yml文件内容放到git仓库,并添加一个新的bootstrap.yml文件
在这里插入图片描述
bootstrap.yml:

#  等价于:http://localhost:8040/userservice/dev
spring:
  application:
    # 资源文件的前缀
    name: userservice
  profiles:
    # 指在git仓库配置的环境
    active: dev
  cloud:
    config:
      uri: http://localhost:8040

解释:userservicedev是指:
在这里插入图片描述
pom.xml依赖:

 <dependency>
 <!--  -->
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

OK,然后照常运行。



zuul路由

Zuul简介
     路由是微服务架构的不可或缺的一部分。例如:”/” 可能映射到你应用主页,/api/users映射到用户服务,/api/shop映射到购物服务。Zuul。Zuul是Netflix出品的一个基于JVM路由和服务端的负载均衡器 当一个UI应用想要代理调用一个或者多个后台服务的时候,Sping cloud创建了一个嵌入的Zuul proxy很方便的开发一个简单的案例。这个功能对于代理前端需要访问的后端服务非常有用,避免了所有后端服务需要关心管理CORS和认证的问题.


创建一个zuul模块
在这里插入图片描述
在pom.xml文件增加依赖:

<dependencies>
	<!-- 开启zuul路由 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
</dependencies>

增加Main方法, ZuulMain.java:

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy // 开启zuul路由
public class ZuulMain {
    public static void main(String[] args) {
        SpringApplication.run(ZuulMain.class, args);
    }
}

增加application.yml文件:

#界面一般是80端口
server:
  port: 80

#给登录微服务设置一个名字
spring:
  application:
    name: zuul

eureka:
  instance:
    prefer-ip-address: true
    hostname: localhost
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
    # 下面是你的注册中心的网址
      defaultZone: http://localhost:8761/eureka/

然后去浏览器运行你原本的代码,路径要改一下:
在这里插入图片描述
下面是我的注册中心
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wufewu/article/details/84781733