spring vault

使用Spring Boot和Spring Cloud的MicroServices –第1部分:概述中 ,我们简要介绍了什么是微服务以及如何使用SpringBootSpringCloud构建微服务。

在这篇文章中,我们将学习:

  • Spring Cloud ConfigVault有什么需求?
  • 创建我们的第一个微服务:catalog-service
  • 创建Spring Cloud Config服务器
  • 使用保管箱存储敏感数据

使用Spring Boot和Spring Cloud的微服务

  • 第1部分:使用Spring Boot和Spring Cloud的MicroServices:概述
  • 第2部分:MicroServices –使用Spring Cloud Config和Vault进行配置管理

Spring Cloud Config和Vault有什么需求?

SpringBoot已经提供了许多选项来外部化配置属性 。 但是,一旦启动应用程序,您将无法在运行时更改这些属性值。 您需要更新属性并重新启动应用程序,以使这些更改生效。

在微服务世界中,可能会有大量的微服务,并且这些微服务的多个实例正在运行。 手动甚至使用自动脚本更新配置属性并重新启动所有这些实例可能不可行。 Spring Cloud Config解决了这个问题。

我们可以创建一个Spring Cloud Config Server,它为我们所有的微服务提供配置值。 我们可以使用gitsvndatabaseConsul作为后端来存储配置参数。 然后,我们可以在我们的微服务中配置Spring Cloud Config服务器的位置,以便在启动应用程序时它将加载所有属性。 除此之外,每当我们更新属性时,我们都可以在微服务中调用/ refresh REST端点,以便它可以重新加载配置更改,而无需重新启动应用程序。

在我们的应用程序中,我们还需要配置各种敏感数据,例如数据库凭据,密钥,令牌等。显然,我们不想将它们存储为纯文本格式。 更好的方法是将它们以加密格式存储,Spring Cloud Config Server提供了对数据进行加密和解密的功能。 更好的是,我们应该使用Vault这样的安全数据存储工具。 Spring Cloud还提供了与Vault的集成,因此我们可以在Vault中存储任何敏感的配置属性。

我已经在Spring Cloud Config Server上写了一些教程,您可以参考:

  • Spring Cloud Config Server简介
  • 使用Spring Cloud Bus自动刷新配置更改

创建我们的第一个微服务:catalog-service

让我们从我们的第一个微服务开始,即catalog-service 。 使用WebJPAMySQLActuatorDevToolsLombok启动器创建一个SpringBoot应用程序。 到目前为止,典型的SpringBoot应用程序还算不错。

您可以在https://github.com/sivaprasadreddy/spring-boot-microservices-series上找到本文的源代码。

首先,让我们实现一个REST端点来提供产品数据,然后将其重构为使用Cloud Config Server。

我们将使用Docker并将MySQL作为Docker容器运行。

docker-compose.yml

version: '3'
services:mysqldb:image: mysql:5.7container_name: mysqldbports:- "3306:3306"environment:MYSQL_ROOT_PASSWORD: adminMYSQL_DATABASE: catalog

如下配置application.properties中的数据源属性:

server.port=8181
logging.level.com.sivalabs=debugspring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/catalog?useSSL=false
spring.datasource.username=root
spring.datasource.password=adminspring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true//expose all the Actuator endpoints
management.endpoints.web.exposure.include=*

创建JPA实体Product.java ,如下所示:

import lombok.Data;
import javax.persistence.*;@Data
@Entity
@Table(name = "products")
public class Product {@Id @GeneratedValue(strategy = GenerationType.AUTO)private Long id;@Column(nullable = false, unique = true)private String code;@Column(nullable = false)private String name;private String description;private double price;
}

如下创建Spring Data JPA存储库ProductRepository.java

import com.sivalabs.catalogservice.entities.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;public interface ProductRepository extends JpaRepository<Product, Long> {Optional<Product> findByCode(String code);
}

现在创建仅委托给ProductRepository的 ProductService 。 我们可以将存储库直接注入到我们的Web层组件(控制器)中,但是今后可能会有一些我不希望放在Controller或存储库中的业务逻辑。

import com.sivalabs.catalogservice.entities.Product;
import com.sivalabs.catalogservice.repositories.ProductRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;@Service
@Transactional
@Slf4j
public class ProductService {private final ProductRepository productRepository;@Autowiredpublic ProductService(ProductRepository productRepository) {this.productRepository = productRepository;}public List<Product> findAllProducts() {return productRepository.findAll();}public Optional<Product> findProductByCode(String code) {return productRepository.findByCode(code);}
}

最后,创建我们的REST控制器ProductController.java

import com.sivalabs.catalogservice.entities.Product;
import com.sivalabs.catalogservice.exceptions.ProductNotFoundException;
import com.sivalabs.catalogservice.services.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("/api/products")
@Slf4j
public class ProductController {private final ProductService productService;@Autowiredpublic ProductController(ProductService productService) {this.productService = productService;}@GetMapping("")public List<Product> allProducts() {return productService.findAllProducts();}@GetMapping("/{code}")public Product productByCode(@PathVariable String code) {return productService.findProductByCode(code).orElseThrow(() -> new ProductNotFoundException("Product with code ["+code+"] doesn't exist"));}
}

创建扩展RuntimeException的 ProductNotFoundException并使用@ResponseStatus(HttpStatus.NOT_FOUND)进行注释。

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;@ResponseStatus(HttpStatus.NOT_FOUND)
public class ProductNotFoundException extends RuntimeException {public ProductNotFoundException() {}public ProductNotFoundException(String message) {super(message);}public ProductNotFoundException(String message, Throwable cause) {super(message, cause);}public ProductNotFoundException(Throwable cause) {super(cause);}
}

让我们将一些示例产品插入我们的数据库。

src / main / resources / data.sql

DELETE FROM products;insert into products(id, code, name, description, price) VALUES
(1, 'P001', 'Product 1', 'Product 1 description', 25),
(2, 'P002', 'Product 2', 'Product 2 description', 32),
(3, 'P003', 'Product 3', 'Product 3 description', 50)
;

好的,现在我们可以启动SpringBoot应用程序并点击http:// localhost:8181 / api / products。 您应该能够看到带有产品信息的JSON响应。

创建Spring Cloud Config服务器

我们将使用Git后端创建Spring Cloud Config Server。 Spring Cloud Config Server只是一个SpringBoot项目。 使用Config Server启动器创建一个SpringBoot项目。

配置git存储库的位置,我们将所有配置文件存储在application.properties文件中。

spring.config.name=configserver
server.port=8888spring.cloud.config.server.git.uri=https://github.com/sivaprasadreddy/microservices-config-repo
spring.cloud.config.server.git.clone-on-start=truemanagement.endpoints.web.exposure.include=*

现在,使用@EnableConfigServer注释入口点类。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {public static void main(String[] args) {SpringApplication.run(ConfigServerApplication.class, args);}
}

而已。 这是创建Spring Cloud Config Server所需要做的一切,仅需要在git存储库中添加特定于应用程序的配置文件。

如果您已经准备好编写一堆代码来创建Spring Cloud Config Server,请您失望:-)。

重构目录服务以使用Config Server

我们的目录服务将成为Config Server的客户端。 因此,让我们将Config Client启动程序添加到catalog-service ,这将添加以下依赖性。

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

确保您还添加了spring-cloud-dependencies BOM表并在<properties>部分中。

使用Spring Cloud Config Server时,属性加载过程分多个阶段进行,首先加载bootstrap.properties/ yml,然后再从配置服务器加载。

因此,让我们将application.properties重命名为bootstrap.properties并将其更新为具有以下属性。

spring.application.name=catalog-service
server.port=8181
management.endpoints.web.exposure.include=*
spring.cloud.config.uri=http://localhost:8888

在这里,我们配置了Config Server的位置,并使用spring.application.name将名称命名为catalog-service

现在,我们需要将catalog-service的所有属性添加到catalog-service.properties中 ,并将其提交/推送到git repo microservices-config-repo中

microservices-config-repo / catalog-service.properties

logging.level.com.sivalabs=debugspring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/catalog?useSSL=false
spring.datasource.username=root
spring.datasource.password=adminspring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

您还可以为不同的文件(例如catalog-service-qa.propertiescatalog-service-prod.properties等)添加单独的配置文件。

现在,首先启动Config Server应用程序,然后再启动目录服务应用程序。 这应该工作正常。 您可以在启动时检查控制台日志,说明目录服务正在从配置服务器http:// localhost:8888 /获取属性。

现在我们离目标还差得很近,但我们仍以纯文本格式存储凭据。 让我们将敏感的配置属性移动到Vault。

使用保管箱存储敏感数据

保管箱是用于安全存储和访问机密的工具。 您可以在https://www.vaultproject.io/intro/index.html上了解有关Vault的更多信息。 Vault是一个二进制文件,您可以从https://www.vaultproject.io/downloads.html下载。

现在,使用以下命令以开发人员模式启动Vault:

$ Vault服务器-dev

在控制台中,您可以查看有关如何使用保险柜和根令牌的信息
打开一个新的终端窗口,设置VAULT_ADDR环境变量。

$ export VAULT_ADDR ='http://127.0.0.1:8200'

注意:Vault开发模式仅用于开发目的,并不用于生产用途。

我们可以使用Vault write secret / somename key1 = value1 key2 = value2向Vault 写入机密
我们还可以将所有机密信息放入JSON文件中,也可以从该文件中写入。 让我们使用MySQL数据库凭据创建JSON文件并写入Vault。

catalog-service-credentials.json

{ "spring.datasource.username": "root", "spring.datasource.password": "admin"
}

$保险库文件写秘密/目录服务@ catalog-service-credentials.json

您可以通过运行Vault read secret / catalog-service来验证值。

我们可以使用Docker自动化设置保管库和使用机密初始化的整个过程。 请查看github上的源存储库以了解如何做,这是一种实现方法。

现在,已使用秘密配置和初始化了Vault。 让我们重构目录服务以使用保管库。

Vault配置启动器添加到目录服务中 ,这将添加以下依赖项。

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

microservices-config-repo / catalog-service.properties中删除以下凭据,然后提交。

spring.datasource.username=root
spring.datasource.password=admin

bootstrap.properties中添加保管库配置属性。

spring.cloud.vault.host=localhost
spring.cloud.vault.port=8200
spring.cloud.vault.scheme=http
spring.cloud.vault.authentication=token
spring.cloud.vault.token=934f9eae-31ff-a8ef-e1ca-4bea9e07aa09

我们已经使用基于令牌的身份验证配置了Vault属性,并配置了在启动Vault服务器时在控制台日志中打印的“ Root Taken”

我们都准备好了。 我们将服务属性移至外部配置服务器,并将敏感数据移至Vault。

现在启动配置服务器和目录服务,它应该可以正常工作。

摘要

在本文中,我们学习了如何使用Spring Cloud Config来外部化配置属性以及如何使用Vault来存储机密。 您可以使用Spring Cloud Bus自动刷新配置更改,如Spring Cloud教程–使用Spring Cloud Bus自动刷新配置更改中所述。

您可以在https://github.com/sivaprasadreddy/spring-boot-microservices-series上找到本文的源代码。

在下一篇文章中,我们将研究如何使用Netflix Eureka进行服务注册和服务发现

翻译自: https://www.javacodegeeks.com/2018/03/microservices-part-2-configuration-management-spring-cloud-config-vault.html

spring vault

spring vault_微服务–第2部分:使用Spring Cloud Config和Vault进行配置管理相关推荐

  1. 微服务为什么一定要选spring cloud?

    作者:董添 李秉谦 || 网易乐得技术团队 来自:http://tech.lede.com/ 现如今微服务架构十分流行,而采用微服务构建系统也会带来更清晰的业务划分和可扩展性.同时,支持微服务的技术栈 ...

  2. spring boot 微服务集群 + 注册中心

    spring boot 微服务框架下载地址: https://start.spring.io/ 注册中心 Eureka Server提供服务注册服务,各个节点启动后,会在Eureka Server中进 ...

  3. Docker容器及Spring Boot微服务应用

    2019独角兽企业重金招聘Python工程师标准>>> Docker容器及Spring Boot微服务应用 1 什么是Docker 1.1 Docker的出现 问题一:项目实施环境复 ...

  4. 分布式和微服务区别_深度解析spring cloud分布式微服务的实现

    分布式系统 微服务就是原来臃肿的项目拆分为多个模块互不关联.如:按照子服务拆分.数据库.接口,依次往下就更加细粒度,当然运维也就越来越难受了. 分布式则是偏向与机器将诺大的系统划分为多个模块部署在不同 ...

  5. 微服务配置中心实战:Spring + MyBatis + Druid + Nacos

    转载自  微服务配置中心实战:Spring + MyBatis + Druid + Nacos 很多基于 Spring MVC 框架的 Web 开发中,Spring + MyBatis + Druid ...

  6. 微服务为什么离不开spring cloud?

    转载自  微服务为什么离不开spring cloud? 现如今微服务架构十分流行,而采用微服务构建系统也会带来更清晰的业务划分和可扩展性.同时,支持微服务的技术栈也是多种多样的,本系列文章主要介绍这些 ...

  7. Spring Boot微服务的黑匣子测试是如此简单

    当我需要进行原型设计,概念验证或在空闲时间使用一些新技术时,开始新项目对于Maven来说总是有点烦人. 不得不说,设置Maven项目并不难,您可以使用Maven原型. 但是原型通常是过时的. 谁想玩旧 ...

  8. Spring构建微服务

    Spring构建微服务 此文为译文,原文地址 介绍 本文通过一个使用Spring.Spring Boot和Spring Cloud的小例子来说明如何构建微服务系统. 我们可以通过数个微服务组合成一个大 ...

  9. 谷粒商城微服务分布式基础篇二—— Spring Cloud Alibaba、Nacos注册与发现

    文章目录 Spring Cloud Alibaba--微服务开发 Spring Cloud Alibaba是什么?  主要功能  组件 为什么不使用Spring Cloud 使用 Nacos Disc ...

最新文章

  1. android keytool 不是内部命令或外部命令在 (win7下不能用的解决方法)
  2. rabbitmq beam.smp cpu利用率过高
  3. Subsonic使用中
  4. Mozilla “Common Voice” 开源语音识别项目
  5. linux线程和进程详解,linux 进程和线程简介
  6. liferay 点击build service 出现Cloud not reserve enough space for object heap
  7. [react] 在React中组件的props改变时更新组件的有哪些方法?
  8. 为什么链接不上mysql数据库_java链接不上数据库,怎么解决!
  9. Cream Finance已批准将BAC作为抵押资产
  10. 03 Python爬虫之Requests网络爬取实战
  11. ORCAD 16.6使用说明及技巧
  12. 数据挖掘应用实例分析
  13. CAD2021下载AutoCAD2021下载AutoCAD安装详细教程
  14. 大学计算机网络实验网线制作,计算机网络实验报告 网线的制作.doc
  15. matlab 数据导入
  16. 2023养老展/山东养老服务业展/济南老年用品展/老龄产业展
  17. 用户生命周期价值及产品运营策略
  18. linux内核源码—编程之路
  19. App Store审核条款更新:WWDC 2016重写版本
  20. VMware Fusion设置静态IP+端口转发(macOS)+内网穿透

热门文章

  1. 屏幕开发-屏幕文本的翻译
  2. java拼音识别声调_Java源代码计算出拼音的声调字母是哪个
  3. Zabbix-监控redis以及使用redis加速php项目
  4. 论文参考文献插入方法,页眉设置
  5. u8g2库stm32移植记录(硬件IIC)
  6. 汽车轮胎,补一下常识
  7. 阿里云高效云盘在线扩容
  8. 三菱FX3U——ST编程定时器和计数器
  9. 《AUTOSAR谱系分解(ETAS工具链)》之Pdus(SystemPdu)
  10. 20144303 《Java程序设计》第二次实验实验报告