1. 搭建Spring Cloud Config配置中心(见上一篇博客)
2. 创建微服务项目bounter-simon-app,pom文件如下:
<?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>cn.bounter</groupId> <artifactId>bounter-simon-app</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>bounter-simon-app</name> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> <spring-cloud.version>Finchley.SR1</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3. 配置从配置中心获取配置信息,application.properties文件如下:
server.port=8081 # 配置中心仓库的配置文件名 spring.application.name=simon # 配置中心服务器地址 spring.cloud.config.uri=http://localhost:8888
4.控制器返回从配置中心获取到的配置信息,SimonController.java 内容如下:
@RestController @CrossOrigin @RequestMapping("/api/simon") public class SimonController { @Value("${name}") private String name; @GetMapping("/name") public ResponseData<?> get() { return new ResponseData<>().success().data(name); } }
5. 启动bounter-simon-app服务,浏览器访问:http://localhost:8081/api/simon/name,页面如下:
{ success: true, data: "simon", errorMsg: null, timestamp: 1534917807, sign: null }
data里就显示了从配置中心获取到的name属性值,是不是觉得很简单啊,那就自己动手试一试吧!
源代码Github地址:
https://github.com/13babybear/bounter-simon-app
https://github.com/13babybear/bounter-susan-app
原文地址:https://www.cnblogs.com/gdufs/p/9517216.html
时间: 2024-11-06 03:41:13