springcloud~配置中心的使用


配置中心作為springcloud里最底層的框架,所發揮的意思是舉足輕重的,所以的組件的配置信息都可以通過springcloud config來管理,它會把配置信息分布式的存儲到git上,所以信息安全這塊可以放心,其它應用程序在更新配置時,直接在遠程GIT倉庫更新即可,而且更新后自動同步到對應的程序里,不需要重啟這個應用程序!

配置服務-服務端,最底層應用

依賴包

dependencies {
    compile('org.springframework.cloud:spring-cloud-config-server',
            'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server'
    )
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

配置項

server:
  port: 8200
spring:
  application:
    name: lind-config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/bfyxzls/lindconfig.repo.git/
          search-paths: config-repo
          username: bfyxzls@sina.com
          password: 糹
eureka:
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${server.port}
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

啟動代碼

@EnableDiscoveryClient
@EnableConfigServer
@SpringBootApplication
class Application {

  public static void main(String[] args) {
    // demo http://localhost://8200/email-svt.yml
    SpringApplication.run(Application.class, args);
  }
}

在github上添加對應的倉庫,客戶端的配置文件將會同步到GIT倉庫,建議配置文件采用yml語法!

 

/**************************************************************************************** * 配置服務的路勁規則: * * /{application}/{profile}[/{label}] * /{application}-{profile}.yml * /{label}/{application}-{profile}.yml * /{application}-{profile}.properties * /{label}/{application}-{profile}.properties ****************************************************************************************/

 

倉儲如圖:

查看配置中心服務端是否正常

訪問:http://localhost:8200/email-svt.yml

配置中心-客戶端,遍及在所有應用中

依賴包

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web',
            'org.springframework.cloud:spring-cloud-starter-config',
            'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

配置項

spring:
  application:
    name: email #注意這里的email是指配置中心git倉庫里yml文件的application的部分
  cloud:
    config:
      uri: http://localhost:8200
server:
  port: 8300

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

啟動項

@EnableEurekaClient
@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

我們可以在客戶端使用$Value注解完成配置文件的讀取!

@RestController
public class HomeController {
  @Value("${server.port}") // git配置文件里的key
      String serverPort;

  @RequestMapping("/")
  public String index() {
    return "serverPort=" + serverPort;
  }
}

結果如圖:

感謝各位的閱讀!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM