2.1改造:从eureka向nacos迁移-gateway

阅读 26

2024-12-02

前言

本博客将尝试使用我的另一篇笔记Spring Cloud 10: eureka2 + seata实现分布式事务 中的代码,将它的注册中心和客户端直接替换成nacos。

正文

1.修改整体依赖配置build.gradle

定义alibaba cloud版本号:

2.1改造:从eureka向nacos迁移-gateway_nacos

添加依赖管理:

2.1改造:从eureka向nacos迁移-gateway_nacos_02

别的都不用动,工程根目录的build.gradle就配置完了。

整体配置如下:

plugins {
    id 'java'
    // spring 依赖管理插件
    // https://plugins.gradle.org/plugin/io.spring.dependency-management
    id 'io.spring.dependency-management' version '1.1.6'
    // spring boot系列版本,不需最新,与mavenBom依赖的版本相同就好
    id 'org.springframework.boot' version '3.2.6'
}

ext {
    // spring cloud套装版本号
    // 在 https://mvnrepository.com/ 搜spring-cloud-dependencies可以找到版本列表
    set('springCloudVersion', "2023.0.2")
    // spring cloud alibaba 套装版本
    set('alibabaCloudVersion', "2023.0.1.3")
}

subprojects {
    apply plugin: 'java'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'

    group = 'com.hao1st'
    repositories {
        mavenCentral()
    }

    // 编译和打包时将xml文件也一同编译,idea可用
    sourceSets.main.resources.srcDirs=["src/main/java","src/main/resources"]

    dependencyManagement {

        imports {
            mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
            mavenBom "com.alibaba.cloud:spring-cloud-alibaba-dependencies:${alibabaCloudVersion}"
        }
    }

    dependencies {
        developmentOnly 'org.springframework.boot:spring-boot-devtools'
        testImplementation 'org.springframework.boot:spring-boot-starter-test'
    }

    test {
        useJUnitPlatform()
    }
}

2.删掉eureka模块

eureka模块是eureka注册中心,我们已经运行了nacos注册中心了,不需要这个模块了,把它删掉。

2.1改造:从eureka向nacos迁移-gateway_nacos_03

3.修改网关模块gateway

首先是修改依赖配置build.gradle.

eureka-client依赖不要了,换成nacos的

2.1改造:从eureka向nacos迁移-gateway_nacos_04

2.1改造:从eureka向nacos迁移-gateway_gateway_05

完整配置:

version = '0.0.1-SNAPSHOT'

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
    implementation 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery'

}

接下来修改yml文件,eureka的配置删掉:

2.1改造:从eureka向nacos迁移-gateway_gateway_06

配置nacos注册中心地址,属性是spring.cloud.nacos.discovery.server-addr

2.1改造:从eureka向nacos迁移-gateway_gradle_07

完整配置如下:

server:
  port: 9001
#服务名
spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      filter:
        remove-non-proxy-headers:
          headers:
            - dummy
      # 服务发现配置,动态路由
      discovery:
        locator:
          enabled: true
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

哦了,我们现在可以启动gateway模块了,启动起来之后,在nacos的服务列表页面可以看见gateway已经注册,可以说gateway从eureka向nacos过渡还是很平滑的。

2.1改造:从eureka向nacos迁移-gateway_nacos_08

参考文献

1.基于Spring Cloud、Nacos搭建微服务项目 - 掘金

精彩评论(0)

0 0 举报