四、SpringBoot整合Apollo

发布时间 2023-06-28 21:38:10作者: shigp1

Apollo非常支持与Spring和SpringBoot的整合。这里选择SpringBoot 2.7.9,java选择jdk17。添加依赖:

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

     <dependency>
        <groupId>com.ctrip.framework.apollo</groupId>
        <artifactId>apollo-client</artifactId>
        <version>2.1.0</version>
    </dependency>

apollo-client选择2.1.0版本。

 

在application.properties配置:

server.port=8000

apollo.bootstrap.enabled=true
apollo.cache-dir=/home/shigp/文档/idea/apollo-demo/src/main/
apollo.meta=http://localhost:8080
apollo.bootstrap.namespaces = application

app.id=my_app001

apollo.meta配置Apollo的META Server的地址。apollo.bootstrap.enabled启用Apollo配置。apollo.cache-dir配置Apollo本地缓存的位置。apollo.bootstrap.namespaces指定apollo的namespace。app.id指定项目的appId。

 

在启动类上加@EnableApolloConfig

 

新增Controller:

@RestController
public class MyController {
    @Value("${my_value}")
    private String myValue;

    @RequestMapping("/myValue")
    public String myValue() {
        return myValue;
    }
}

 

在Apollo上配置为:
 

 

启动后访问http://localhost:8000/myValue,看到12346。在Apollo上修改配置并发布:
 

 

在不启动应用的情况下访问http://localhost:8000/myValue,看到12346avfgh。配置自动更新了。