带有Spring Cloud Config和JHipster的Java微服务

如今,使用Java和Spring Boot开发微服务架构非常流行。 它绝对是Java生态系统中最受欢迎的组合之一。 如果需要任何证据,只需看看过去几年出现的所有类似框架:MicroProfile,Micronaut和Quarkus,仅举几例。

Spring Boot于2014年首次发布时,便为Spring生态系统提供了急需的火花。它没有使Java开发人员配置其Spring Bean的所有方面,而是提供了“启动程序”,其中包含具有默认设置的预配置Bean。 这样可以减少Java代码,还可以通过以下方式覆盖默认值:application.properties文件。 是的,有许多方法可以在Spring Boot应用程序中修改默认值,但现在我将跳过。

In a previous tutorial on Java Microservices with Spring Boot and Spring Cloud, I showed how you can use OAuth 2.0 and OpenID Connect to secure everything. One of the problems with this example is that you have to configure the OIDC properties in each application. This can be a real pain if you have hundreds of microservices. Yes, you could define them as environment variables and this would solve the problem. However, if you have different microservices stacks using different OIDC client IDs, this approach will be difficult.

Java Microservices with Spring Cloud Config

小号pring Cloud Config is a project that provides externalized configuration for distributed systems. Spring Cloud Config has server and client components. You can configure the server to read its configuration from the file system or a source code repository, like Git. On the client, you configure things in a bootstrap configuration file to get configuration data from the server. In a microservices environment, this provides an elegant way to configure all your microservices from a central location.

今天,我想向您展示这是如何工作的,并使用我曾经使用过的最时髦的微服务解决方案进行演示。

Use JHipster to Generate a Java Microservices Architecture

ĴHipster is a development platform to generate, develop, and deploy Spring Boot + { Angular or React or Vue } applications. In addition, it supports creating Spring-based microservice architectures. In fact, if you create microservices projects and choose OAuth 2.0 / OIDC for authentication, you’ll be using code that’s very similar to the aforementioned example.

To use JHipster, you’ll need to have Node.js installed. You can also use start.jhipster.tech, which is similar to start.spring.io.

安装JHipster的最常见方法是使用npm:

npm install -g generator-jhipster@6.0.1

注意:您可以运行上面没有版本号的命令以获取最新版本的JHipster。 如果是6.x,则本教程应该可以,但是我不能保证可以。

在终端中,创建一个目录来保存要创建的所有项目。 例如,吉普斯特。

创建一个apps.jh文件放在此目录中,并将以下代码放入其中。

application {
  config {
    baseName gateway,
    packageName com.okta.developer.gateway,
    applicationType gateway,
    authenticationType oauth2,
    prodDatabaseType postgresql,
    serviceDiscoveryType eureka,
    testFrameworks [protractor]
  }
  entities Blog, Post, Tag, Product
}

application {
  config {
    baseName blog,
    packageName com.okta.developer.blog,
    applicationType microservice,
    authenticationType oauth2,
    prodDatabaseType postgresql,
    serverPort 8081,
    serviceDiscoveryType eureka
  }
  entities Blog, Post, Tag
}

application {
  config {
    baseName store,
    packageName com.okta.developer.store,
    applicationType microservice,
    authenticationType oauth2,
    databaseType mongodb,
    devDatabaseType mongodb,
    prodDatabaseType mongodb,
    enableHibernateCache false,
    serverPort 8082,
    serviceDiscoveryType eureka
  }
  entities Product
}

entity Blog {
  name String required minlength(3),
  handle String required minlength(2)
}

entity Post {
  title String required,
  content TextBlob required,
  date Instant required
}

entity Tag {
  name String required minlength(2)
}

entity Product {
  title String required,
  price BigDecimal required min(0),
  image ImageBlob
}

relationship ManyToOne {
  Blog{user(login)} to User,
  Post{blog(name)} to Blog
}

relationship ManyToMany {
  Post{tag(name)} to Tag{post}
}

paginate Post, Tag with infinite-scroll
paginate Product with pagination

microservice Product with store
microservice Blog, Post, Tag with blog

// will be created under 'docker-compose' folder
deployment {
  deploymentType docker-compose
  appsFolders [gateway, blog, store]
  dockerRepositoryName "jmicro"
  consoleOptions [zipkin]
}

ŤIP: You’ll want to change the dockerRepositoryName in the JDL above to use your Docker Hub username if you want to publish your containers. This is not a necessary step to complete this tutorial.

This code is JDL (JHipster Domain Language) and you can use it to define your app, its entities, and even deployment settings. You can learn more about JDL in JHipster’s JDL documentation. Below is a screenshot of JDL Studio, which can be used to edit JDL and see how entities related to each other.

JDL Studio

您刚放入的JDLapps.jh定义了三个应用程序:

  • 网关:微服务的单个入口,其中将包括UI组件。博客: a 博客 service that talks to PostgreSQL.商店: a 商店 service that uses MongoDB.

运行以下命令以在您的计算机中创建这些项目吉普斯特夹。

jhipster import-jdl apps.jh

这将并行创建所有三个项目。

Create Docker Images for Microservice Apps

为Docker Compose生成配置时,会向控制台发出警告。

WARNING! Docker Compose configuration generated, but no Jib cache found
If you forgot to generate the Docker image for this application, please run:
To generate the missing Docker image(s), please run:
  ./mvnw -Pprod verify jib:dockerBuild in /Users/mraible/java-microservices-examples/jhipster/gateway
  ./mvnw -Pprod verify jib:dockerBuild in /Users/mraible/java-microservices-examples/jhipster/blog
  ./mvnw -Pprod verify jib:dockerBuild in /Users/mraible/java-microservices-examples/jhipster/store

为了使使用一个命令创建Docker映像更容易,请创建一个聚合器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.okta.developer</groupId>
    <artifactId>jhipster-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>jhipster-parent</name>
    <modules>
        <module>gateway</module>
        <module>blog</module>
        <module>store</module>
    </modules>
</project>

Then "just jib it" using Jib.

mvn -Pprod verify com.google.cloud.tools:jib-maven-plugin:dockerBuild

ŤIP: If you don’t have Maven installed, use brew install maven on a Mac, or see Maven’s installation docs.

[INFO] Skipping containerization because packaging is 'pom'...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Gateway 0.0.1-SNAPSHOT ............................. SUCCESS [02:44 min]
[INFO] Blog 0.0.1-SNAPSHOT ................................ SUCCESS [ 34.391 s]
[INFO] Store 0.0.1-SNAPSHOT ............................... SUCCESS [ 28.589 s]
[INFO] jhipster-parent 1.0.0-SNAPSHOT ..................... SUCCESS [  1.096 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 03:49 min
[INFO] Finished at: 2019-05-17T07:44:39-06:00
[INFO] ------------------------------------------------------------------------
Execution time: 3 min. 50 s.

Run Your Java Microservices Stack with Docker Compose

一切构建完成后,进入CD码头工人组成目录并启动所有容器。

cd docker-compose
docker-compose up -d

小费:去除-d如果要在当前终端窗口中查看所有日志。

It will take several minutes to start all eight of your containers. You can use Kitematic to monitor their startup progress if you like.

Creating docker-compose_gateway-app_1 ... done
Creating docker-compose_gateway-postgresql_1 ... done
Creating docker-compose_blog-app_1 ... done
Creating docker-compose_store-mongodb_1 ... done
Creating docker-compose_keycloak_1 ... done
Creating docker-compose_blog-postgresql_1 ... done
Creating docker-compose_jhipster-registry_1 ... done
Creating docker-compose_store-app_1 ... done

JHipster Registry for Service Discovery with Java Microservices

该微服务堆栈使用Eureka进行服务发现,就像准系统Spring Boot + Spring Cloud示例一样。 这是由JDL中每个应用程序的以下行确定的。

serviceDiscoveryType eureka

When you select eureka for service discovery, JHipster Registry is used. This application is very similar to Eureka Server, except it has an Angular UI and includes Spring Cloud Config, among other features.

ŤIP: JHipster also supports Hashicorp Consul for service discovery.

由于您选择了OAuth 2.0 / OIDC进行身份验证,因此您需要在自己的帐户中创建一个条目主机文件(/etc/主机在Linux / Mac上,C:\Windows\System32\Drivers\etc\主机在Windows上)。

127.0.0.1 keycloak

这是因为Docker网络可以识别钥匙斗篷作为注册的主机名,但它还会将您重定向到钥匙斗篷。 如果没有该浏览器,您的浏览器将无法识别该主机名。主机条目。

打开浏览器并导航到http://本地主机:8761。 您将被重定向到Keycloak进行登录。 输入管理员/管理员凭据,您将被重定向回JHipster Registry。 您会看到所有微服务实例均已注册。

JHipster Registry

导航http://本地主机:8080,点击登入,您将登录到网关。 你可以去实体 > 博客并添加一个博客。

Blog List

去实体 > 产品您也可以添加产品。

Product List

很漂亮,你不觉得吗? 🤓

Configure JHipster Microservices to Use Okta for Identity

在基本的Spring Boot + Spring Cloud设置中看到的问题之一是必须配置okta.oauth2。*每个微服务的属性。 JHipster不使用Okta Spring Boot启动器。 它用oauth2-client和oauth2-资源服务器Spring Boot入门代替。 OAuth 2.0的配置包含在每个应用的src / main / resources / config / application.yml文件。

spring:
  ...
  security:
    oauth2:
      client:
        provider:
          oidc:
            issuer-uri: http://localhost:9080/auth/realms/jhipster
        registration:
          oidc:
            client-id: internal
            client-secret: internal

Why Okta?

You might be wondering why you should use Okta instead of Keycloak? Keycloak works great for development and testing, and especially well if you’re on a plane with no wi-fi. However, in production, you want a system that’s always on. That’s where Okta comes in. To begin, you’ll need to create an Okta account and an application with it.

Create a Web Application in Okta

Log in to your Okta Developer account (or sign up if you don’t have an account).

  1. 来自应用领域页面,选择添加申请。在“创建新应用程序”页面上,选择网页。为您的应用起一个令人难忘的名称,然后添加http:// localhost:8080 / login / oauth2 / code / okta作为登录重定向URI,选择刷新令牌(此外授权码),然后点击完成。要配置注销以在JHipster中工作,编辑您的应用,添加http://本地主机:8080作为注销重定向URI,然后单击保存。

Configure Your OpenID Connect Settings with Spring Cloud Config

您可以使用JHipster Registry中的Spring Cloud Config来代替Okta修改每个应用程序。 打开docker-compose / central-server-config / application.yml并添加您的Okta设置。

客户端ID和密码可在您的应用设置页面上找到。 您可以在下面找到发行人API > 授权服务器。

spring:
  security:
    oauth2:
      client:
        provider:
          oidc:
            issuer-uri: https://{yourOktaDomain}/oauth2/default
        registration:
          oidc:
            client-id: {yourClientId}
            client-secret: {yourClientSecret}

注册表,网关,博客和存储应用程序均已配置为在启动时读取此配置。

重新启动所有容器,以使此配置生效。

docker-compose restart

登录之前,您需要为JHipster Registry添加重定向URI,确保您的用户位于ROLE_ADMIN组,并且该组包含在ID令牌中。

登录到Okta仪表板,编辑OIDC应用,然后添加以下登录重定向URI:

  • http:// localhost:8761 / login / oauth2 / code / oidc

您还需要添加一个注销重定向URI:

  • http://本地主机:8761

然后,点击保存。

Create Groups and Add Them as Claims to the ID Token

默认情况下,JHipster配置为与两种类型的用户一起使用:管理员和用户。 Keycloak会自动为用户和组配置,但是您需要为Okta组织进行一些一次性配置。

创建一个ROLE_ADMIN组(用户数 > 团体 > 新增群组),并将您的用户添加到其中。 导航API > 授权服务器,然后点击默认服务器。 点击索偿标签和添加声明。 命名团体,并将其包含在ID令牌中。 将值类型设置为团体并将过滤器设置为的正则表达式。*。 请点击创建。

Add Claim

现在当你打http://本地主机:8761要么http://本地主机:8080,系统会提示您使用Okta登录!

JHipster Okta Login

JHipster Okta Success

您如何通过Spring Cloud Config在一个地方配置服务注册表和所有微服务真是太漂亮了,您认为吗? 👌

Configuring Spring Cloud Config with Git

JHipster Registry及其Spring Cloud Config服务器支持两种配置源:本机和吉特。 使用哪一个取决于spring.cloud.config.server.composite属性。 如果你看docker-compose / jhipster-registry.yml,您会看到本机 is enabled和吉特已被注释掉。

- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_TYPE=native
- SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_SEARCH_LOCATIONS=file:./central-config
# - SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_TYPE=git
# - SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_URI=https://github.com/jhipster/jhipster-registry/
# - SPRING_CLOUD_CONFIG_SERVER_COMPOSITE_0_SEARCH_PATHS=central-config
# For Keycloak to work, you need to add '127.0.0.1 keycloak' to your hosts file

You can see the default configuration for Git at @jhipster/jhipster-registry/central-config/application.yml. You can learn more about application configuration with Spring Cloud Config in JHipster Registry’s documentation. It includes a section on encrypting configuration values.

What About Kotlin Microservices?

在本系列的第一篇文章中,我告诉您了为什么我用Java撰写这篇文章:

"I wrote this post with Java because it’s the most popular language in the Java ecosystem. However, Kotlin is on the rise, according to RedMonk’s programming language rankings from January 2019."

Spring has excellent support for Kotlin, and you can choose it as a language on start.spring.io. JHipster has support for Kotlin too with its Kotlin Blueprint! A new release was published last week that allows you to create Kotlin-based JHipster apps with khipster.

如果您希望我们使用Kotlin写更多文章,请在评论中告诉我们!

Learn More about Spring Cloud Config, Java Microservices, and JHipster

我希望您喜欢学习如何使用JHipster构建Java微服务架构以及如何使用Spring Cloud Config对其进行配置。 您学习了如何从单个JDL文件生成所有内容,如何将应用程序打包在Docker容器中,使用Docker Compose运行它们,以及使用Keycloak和Okta使用OIDC进行身份验证。

You can find all the code shown in this tutorial on GitHub in the jhipster directory.

我们是此博客上的Spring Boot,Spring Cloud和JHipster的忠实拥护者。 这是您可能会发现有趣的其他几篇文章:

Please follow us on Twitter @oktadev and subscribe to our YouTube channel for more Spring and Spring Security tips.

from: https://dev.to//oktadev/java-microservices-with-spring-cloud-config-and-jhipster-14ji

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值