美文网首页
使用 IDEA 从 0 开始搭建 Spring Cloud 微服

使用 IDEA 从 0 开始搭建 Spring Cloud 微服

作者: 把酒对牛 | 来源:发表于2020-06-12 19:03 被阅读0次

以下内容均来源于一个微服务初学者的实践,仅供参考。

微服务架构

首先启动 Spring Cloud Eureka 注册中心,其他部分都作为服务注册到 Eureka ,并通过注册的服务名互相访问。Spring Cloud Config 提供统一的配置信息,供其他服务读取。Provider 生产者服务不直接对外暴露,仅供 Consumer 消费者服务调用。用户通过 Spring Cloud Gateway 统一访问消费者服务。

创建 IDEA 多模块 Maven 项目

首先创建一个空 Maven 项目,然后右键项目 -> New Module ,选择继续创建空 Maven 模块或者使用 Spring Initializr 构建 Spring Cloud 模块。common模块用于存放公共的 lib ,如 dao 、model 、util 等。config-dev 存放配置文件,上传到 git 之后供 Spring Cloud Config 读取。

除了少数像 Spring Cloud Config 、Spring Cloud Gateway 这种独立应用,大部分非空模块都需要添加 spring-boot-starter-web 构建 Web 应用。下图是使用 IDEA 的 Spring Initializr 快速构建新模块。

下面贴上详细的配置文件和注解,bootstrap.yml 具有高优先级,会提前加载并且不会被 application.yml 覆盖,spring.cloud.config 需要配置在 bootstrap.yml 中,否则不能正常从配置中心获取配置信息。

Spring Cloud Eureka

application.yml

server:
  port: 8081
spring:
  application:
    name: spring-eureka-server
eureka:
  client:
    # 单节点不需要注册服务自己
    register-with-eureka: false
    # 单节点不需要同步其他server
    fetch-registry: false
    serviceUrl:
      defaultZone:
        http://localhost:8081/eureka/

HobbyEurekaApplication.java

@SpringBootApplication
@EnableEurekaServer
public class HobbyEurekaApplication {}
Spring Cloud Config

application.yml

server:
  port: 8082
spring:
  application:
    name: spring-config-server
  # 优先加载带profile的配置文件,用于项目不同阶段配置信息切换
  profiles:
    active: dev
eureka:
  client:
    serviceUrl:
      defaultZone:
        http://localhost:8081/eureka/

application-dev.yml

spring:
  cloud:
    config:
      server:
        git:
          # 测试能否正常读取 http://localhost:8082/database-1.yml
          uri: http://xx.xxx.xxx.xxx:8091/root/hobby.git # 配置git仓库地址
          searchPaths: config-dev # 配置仓库路径
          username: SpringConfig # 访问git仓库的用户名
          password: *********** # 访问git仓库的用户密码
          default-label: master # 默认分支

HobbyConfigApplication.java

@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class HobbyConfigApplication {}
Spring Cloud Gateway

bootstrap.yml

spring:
  cloud:
    config:
      discovery:
        enabled: true
        serviceId: spring-config-server
      # 需要在bootstrap.yml中预先加载配置,否则application.yml中无法引用
      name: gateway
eureka:
  client:
    serviceUrl:
      defaultZone:
        http://localhost:8081/eureka/

config-dev/gateway.yml

server:
  port: 80
spring:
  application:
    name: spring-gateway
  cloud:
    gateway:
      enabled: true
      routes:
        - id: test_consumer
          uri: http://127.0.0.1:8084
          predicates:
            - Path=/consumer/**
          filters:
            # 去掉第一个前缀/consumer
            - StripPrefix=1

HobbyGatewayApplication.java

@SpringBootApplication
@EnableDiscoveryClient
public class HobbyGatewayApplication {}
provider-xxx

在 Spring Cloud Gateway 的配置中已经展示过如何从 config-dev 配置仓库中读取配置文件。spring.cloud.config 和 eureka.client 都已经在 bootstrap.yml 中配置过,接下来不做赘述。多模块项目中扫描其他模块的 mybatis 文件需要做额外的配置。
application.yml

server:
  port: 8083
spring:
  application:
    name: hobby-provider-test
mybatis:
  # 数据库映射实体类包路径
  type-aliases-package: com.fun.hobbycommon.entity
  # mapper.xml扫描路径,classpath*扫描所有模块,默认无法读取hobby-common模块中的mapper.xml
  mapper-locations: classpath*:/mapper/*.xml

HobbyProviderTestApplication.java

@SpringBootApplication
@EnableDiscoveryClient
// 扫描所有包内的component,否则IDEA解析不到common模块的组件,会报错,虽然不影响使用
@ComponentScan(basePackages={"com.fun"})
// 扫描mapper接口
@MapperScan(basePackages={"com.fun.hobbycommon.dao"})
public class HobbyProviderTestApplication {}
consumer-xxx

消费者调用生产者可以使用 Feign 声明式服务调用。
HobbyConsumerTestApplication.java

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class HobbyConsumerTestApplication {}

TestFeignService.java

@FeignClient(name = "hobby-provider-test", path = "/test")
public interface TestFeignService {
    // 访问 hobby-provider-test 服务的 /test/testQuery
    @RequestMapping("/testQuery")
    String testQuery();
}

TestServiceImpl.java

@Service
public class TestServiceImpl implements ITestService {

    @Autowired
    private TestFeignService testFeignService;

    @Override
    public String queryTest() {
        // 声明式服务调用
        return testFeignService.testQuery();
    }
}

项目启动顺序

Spring Cloud Eureka >> Spring Cloud Config >> Spring Cloud Gateway >> 其他服务

Gitlab 搭建

微服务架构能够将各种服务解耦,单独部署,配合 devops 才能展现出真正的威力,否则运维的工作会苦不堪言。gitlab 目前已经集成了 devops 功能,只要在项目中添加.gitlab-ci.yml,push 到 Gitlab 之后就会自动执行配置的命令,这里简单介绍一下 gitlab 的安装部署。
CentOS7 自带的 Git 版本号是 1.8.3.1 ,需要更新,否则 Gitlab Runner 在进行自动构建的时候会报错 fatal: git fetch-pack: expected shallow list ,更新步骤如下:

# 删除旧版本 Git
sudo yum remove git
# 安装新版本 Git
sudo yum -y install https://packages.endpoint.com/rhel/7/os/x86_64/endpoint-repo-1.7-1.x86_64.rpm
sudo yum install git

Gitlab 安装官方文档
Gitlab Runner 安装官方文档

修改 Gitlab 配置文件

配置文件的地址 /etc/gitlab/gitlab.rb
修改配置文件的操作:

# 停止 Gitlab
gitlab-ctl stop
# 修改配置文件
vim /etc/gitlab/gitlab.rb
# 根据配置文件重新配置
gitlab-ctl reconfigure
# 重启 Gitlab
gitlab-ctl restart

常用配置:

# git clone 的地址
external_url 'http://xx.xxx.xxx.xxx:8091'
# gitlab 仓库保存的位置
git_data_dirs({
"default" => { "path" => "/data/gujie/gitlab" }
})
# 邮箱配置,没有会导致 Gitlab 就不能发送邮件
gitlab_rails['smtp_enable'] = true
gitlab_rails['smtp_address'] = "smtp.163.com"
gitlab_rails['smtp_port'] = 465
gitlab_rails['smtp_user_name'] = "xxxxxxx@163.com"
gitlab_rails['smtp_password'] = "******"
gitlab_rails['smtp_domain'] = "163.com"
gitlab_rails['smtp_authentication'] = "login"
gitlab_rails['smtp_enable_starttls_auto'] = true
gitlab_rails['smtp_tls'] = true
gitlab_rails['smtp_openssl_verify_mode'] = 'none'
gitlab_rails['gitlab_email_from'] = "xxxxxxx@163.com"
user["git_user_email"] = "xxxxxxx@163.com"

相关文章

网友评论

      本文标题:使用 IDEA 从 0 开始搭建 Spring Cloud 微服

      本文链接:https://www.haomeiwen.com/subject/wndgtktx.html