配置中心的微服务有了不同环境的配置信息,其他微服务可以作为客户端获取配置中心的配置信息。
在product-service中加入spring-cloud-config-client的依赖。
再增加一个配置文件bootstrap.yml,内容为配置中心的URL。
启动这个微服务就可以加载到远程的配置,为了验证加载到的信息,可以新建一个类映射配置信息。
package com.lpplpp.product.app.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class JdbcConfiguration {
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.driverClassName}")
private String driverClassName;
@Override
public String toString() {
return "JdbcConfiguration{" +
"url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", driverClassName='" + driverClassName + '\'' +
'}';
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
}
在ProductController中加入一个访问路径/config,从浏览器就可以访问到配置信息。
package com.lpplpp.product.app.controller;
import com.lpplpp.product.app.config.JdbcConfiguration;
import com.lpplpp.product.app.model.Product;
import com.lpplpp.product.app.service.ProductService;
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.RestController;
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@Autowired
private JdbcConfiguration jdbcConfiguration;
@GetMapping(value = "product/{id}")
public Product getById(@PathVariable("id") Long id) {
return productService.getById(id);
}
@GetMapping(value = "config")
public String getConfig() {
return jdbcConfiguration.toString();
}
}
在配置中心的git目录中新增配置文件product-service-dev.properties以及product-service-prod.properties,内容和之前的配置文件差不多。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/productdb?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
重启配置中心微服务和产品微服务,访问http://localhost:8080/config可以看到
访问结果:
JdbcConfiguration{url='jdbc:mysql://127.0.0.1:3306/dev?useUnicode=true&characterEncoding=utf8', username='root', password='123456', driverClassName='com.mysql.jdbc.Driver'}
修改下product-service-dev.properties里面的内容提交到git,再重启产品微服务访问http://localhost:8080/config查看更新。
访问结果:
JdbcConfiguration{url='jdbc:mysql://127.0.0.1:3306/productdb?useUnicode=true&characterEncoding=utf8', username='root', password='123456', driverClassName='com.mysql.jdbc.Driver'}