Spring Cloud(二):Spring Cloud Con

作者: 神易风 | 来源:发表于2018-08-08 21:42 被阅读15次

    因为涉及到多个子工程,这种情况比较适合gradle担当构建工具。
    配置build.gradle

    buildscript {
       
        ext {
            springBootVersion = '2.0.3.RELEASE'
        }
        repositories {
              mavenLocal()
              maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
              mavenCentral()
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        }
    }
    
    //这个属性gradle 用来配置这个项目下所有子项目共同属性,根项目没有此属性
    subprojects{
        apply plugin: "java"
        apply plugin: "eclipse"
        apply plugin: "io.spring.dependency-management"
        apply plugin: "org.springframework.boot"
        
        repositories {
         mavenLocal()
         maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
         mavenCentral()
        }
        
        dependencyManagement {
            imports {
                mavenBom "org.springframework.boot:spring-boot-dependencies:${springBootVersion}"
                mavenBom "org.springframework.cloud:spring-cloud-dependencies:Finchley.RELEASE"
            }
        }
        
        dependencies {
        testImplementation 'junit:junit:4.12'
        compile('org.springframework.boot:spring-boot-starter-web')
        compile("org.springframework.boot:spring-boot-starter-actuator")
       // runtime('org.springframework.boot:spring-boot-devtools')
        testCompile('org.springframework.boot:spring-boot-starter-test')
       }
         
    }
         //下面子项目配置
       //引入spring cloud config 依赖
       project(":config"){
         dependencies{
           compile('org.springframework.cloud:spring-cloud-starter-config')
           compile('org.springframework.cloud:spring-cloud-config-server')
         }
       }
    
    

    setting.gradle 创建子工程

    rootProject.name = 'cloud'
    include  'config'
    

    然后在在根项目创建子项目目录cloud 以及类路径目录 mkdir p src/main/{java,resources},运行gradle build,spring cloud config入门工程就算构建完成了。

    创建本地文件的spring cloud 配置服务器

    application.yml文件

    server:
      port: 85
    spring:
      profiles:
        active: native
      cloud:
        config:
          server:
            native:
              search-locations:
              - file:///H:/springconfig/
    

    用过spring boot同学,差不多都知道配置什么意思,我就不具体去说明了。我想说明下spring cloud config 上配置信息 ,spring .profiles.active:natvie : 表示使用本地文件存储应用程序配置信息。spring.config.server.native.search-location 表示应用程序数据所在的文件路径,这个配置是一个数组,用-表示多个路径
    创建spring cloud config引导类

    @SpringBootApplication
    @EnableConfigServer //成为spring cloud config server
    public class ConfigCloudApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ConfigCloudApplication.class, args);
        }
    }
    

    在配置文件路径下创建多个yml文件

    image.png
    启动项目,使用浏览器访问http://localhost:85/config/default ,将会看到config.yml配置内容输出
    config.yml

    如果想查看application-dev.yml配置内容,可以访问http://localhost:85/application/dev

    application-dev.yml
    应用程序配置文件的命名约定“应用程序名-环境名称.yml” 用图3更加直观表示
    图3.png
    不单单是这些命名规则,实际上支持的很丰富的
    [/{name}-{profiles}.yml || /{name}-{profiles}.yaml]
    [/{name}/{profiles:.*[^-].*}]
    [/{label}/{name}-{profiles}.yml || /{label}/{name}-{profiles}.yaml]
    [/{name}/{profiles}/{label:.*}]
    [/{name}-{profiles}.json]
    [/{label}/{name}-{profiles}.properties]
    [/{label}/{name}-{profiles}.json]
    [/{name}/{profile}/**]
    [/{name}/{profile}/{label}/**]
    [/{name}/{profile}/{label}/**]
    
    • name 表示 应用名
    • profiles 表示环境名称
    • label 表示分支 一般都是连接git 使用
    • 支持各种各样的文件后缀 .yml、yaml、json、properties等等。

    Spring Cloud Config与客户端集成

    为了更加直观的,引入图4表示,项目的配置文件都从Spring Cloud Config中,使用http://{hostname}/文件名/环境名称 获取到配置文件,Config Server 根据url找到响应的文件,将数据源返回给config client。


    图4.jpg
    创建config client

    文字很难直白清楚,直接上写代码最直观了。一个小demo,创建一个spring data jpa的工程,数据源从Spring Cloud Config获取,向外暴露一个接口,根据id查询数据,我们调用这个接口就知道数据有没有加载成功了。
    引入依赖

    project(":config-client"){
         dependencies{
           compile("org.springframework.cloud:spring-cloud-config-client")  
           compile("org.springframework.boot:spring-boot-starter-data-jpa")
           compile("mysql:mysql-connector-java:5.1.46")
         }
       }
    

    创建实体

    @Entity
    @Table(name = "user")
    public class User {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int id;
        
        private String name;
        
        private String email;
    
    

    创建Repository接口查询数据接口,直接继承CurdRepository

    @Repository
    public interface UserRepository extends CrudRepository<User, Integer> {
    
    }
    
    

    创建启动类

    @SpringBootApplication
    @RestController
    @RefreshScope //自动刷新
    public class ClientApplication {
        
        public static void main(String[] args) {
          SpringApplication.run(ClientApplication.class, args);
        }
        
        @Value("${str}")
        String str;
        
        @Autowired
        private UserRepository userRepository;
        
        @GetMapping("/user/{id}")
        public User index(@PathVariable Integer id) {
            return userRepository.findById(id).get();
        }
        
        @GetMapping("/str")
        public String str() {
            return str;
        }
        
    

    编写配置文件,主要包括应用程序名称,应用程序profile和连接Spring Cloud Config服务的URI。我们在编写这些配置的文件时,会使用bootstrap.yml或不是application.yml,这是因为bootstrap.yml加载等级比application.yml高,并且属性不允许覆盖。
    bootstrap.yml

    server:
      port: 86
    spring: 
      application:
        name: app
      cloud:
        config:
          profile: dev
          uri: http://localhost:85
    management:
      endpoints:
        web:
          exposure:
            include: refresh
    

    spring.application.name 告诉服务器你这个应用程序名称,Spring Cloud Config会找出对应的文件名。
    spring.cloud.config.profile 指定应用程序运行环境文件
    spring.coud.config.url: Spring Cloud Config物理路径
    启动程序,打开浏览器访问 http://localhost:86/user/1 ,出现下图就说明成功了。

    image.png
    可以从日志中知道,读取了那个文件
    image.png
    现在有个问题了,如果我们修改了配置文件,client能否加载到最新的值呢?
    我在配置文件中定义了一个str:aaa的值,有个一个/str的接口会直接返回这个值
    image.png
    如果我们到文件中修改配置文件,将改成str:bbbbb,在访问这个接口返回的数据是否会变吗?
    多刷新几次后,发现根本不会变,这是因为Spring Boot应用程序只会在启动时读取他们的属性,因此Spring Cloud配置服务器中进行修改的属性不会被Spring Boot应用程序自动获取。如果你想修改配置后,又不想启动应用程序,可以在启动类上加上@RefreshScope注解,允许开发人员访问/refresh,这会让Spring Boot应用程序重新读取应用程序配置。使用浏览器访问http://localhost:86/actuator/refresh POST请求,这时再去访问/str就会发现文件自动变成修改后的值了。
    连接git 文件存储
    Spring Cloud Config不仅支持本地文件存储,也支持git远程存储。现在将配置文件存储到GitHub上, image.png

    修改配置,添加git url

    server:
      port: 85
    spring:
      #profiles:
       # active: native
      cloud:
        config:
          server:
            git:
              uri: https://github.com/xiaowu6666/websocket
              search-paths: src/main/resources    #相对目录,如果是根目录可以不写
              #username: 因为使用https 不使用账号,密码也可以clone成功 
              #password: 
    

    使用浏览器访问http://localhost:85/app/dev

    {
      "name": "app",
      "profiles": [
        "dev"
      ],
      "label": null,
      "version": "651047593f90acf2aeb1885e77b624ddfdd3f721",
      "state": null,
      "propertySources": [
        {
          "name": "https://github.com/xiaowu6666/websocket/src/main/resources/app-dev.yml",
          "source": {
            "spring.datasource.url": "jdbc:mysql://localhost/ting?useSSL=false&characterEncoding=utf8",
            "spring.datasource.username": "root",
            "spring.datasource.password": 123123,
            "spring.jpa.database": "mysql",
            "spring.jpa.show-sql": true,
            "spring.jpa.hibernate.ddl-auto": "update",
            "str": "aaa"
          }
        }
      ]
    }
    

    相关文章

      网友评论

        本文标题:Spring Cloud(二):Spring Cloud Con

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