Netflix open source library Archaius

1. What is Archaius?

Archaius is actually an encapsulation and extension of the Apache Common Configuration Library. It provides a set of Java-based configuration APIs. The main features include:

  • Configuration can be dynamically adjusted
  • Configuration support type (Int, Long, Boolean, etc.)
  • High performance and thread safety
  • Provide a framework for pulling configuration, which can dynamically pull the changed configuration from the configuration source
  • Support the callback mechanism, which is automatically invoked when the configuration changes
  • Support JMX MBean, you can view the configuration and modify the configuration through JConsole

Insert picture description here

The core Achaius is called a combination of configuration concepts (Composite Configuration), and can be understood as a simple hierarchical configuration, hierarchical priority and high-priority level configuration will overwrite low priority configuration. Each level can obtain configuration from a configuration source, such as local configuration files, JDBC data sources, remote REST APIs, etc. The configuration source can also dynamically pull changes at runtime. For example, in the above figure, Persisted DB Configuration refers to storing the configuration in a relational database, and the corresponding configuration source will periodically pull changes from the database. The final value of the configuration is determined by the top-level configuration. For example, if multiple levels contain a certain configuration item, the final value seen by the application is the top-most value in the configuration level. The order of configuration layers can be adjusted

The core interface of pull configuration is PolledConfigurationSourcethat Achaius provides two sub-categories: JDBCConfigurationSource (based on database) and URLConfigurationSource (based on URL). Below, we will obtain dynamic properties in a database-based manner.

public interface PolledConfigurationSource {
    
    

    /**
     * Poll the configuration source to get the latest content.
     * 
     * @param initial true if this operation is the first poll.
     * @param checkPoint Object that is used to determine the starting point if the result returned is incremental. 
     *          Null if there is no check point or the caller wishes to get the full content.
     * @return The content of the configuration which may be full or incremental.
     * @throws Exception If any exception occurs when fetching the configurations.
     */
    public PollResult poll(boolean initial, Object checkPoint) throws Exception;    
}

Insert picture description here

2. Obtain dynamic attributes based on the database

1), add archaius dependency

        <dependency>
            <groupId>com.netflix.archaius</groupId>
            <artifactId>archaius-core</artifactId>
            <version>0.6.0</version>
        </dependency>

2), create a database table

CREATE TABLE `my_site_properties` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `property_key` varchar(50) DEFAULT NULL COMMENT '属性的key',
  `property_value` varchar(255) DEFAULT NULL COMMENT '属性的值',
  PRIMARY KEY (`id`),
  UNIQUE KEY `my_site_properties_u1` (`property_key`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

3), configuration class

@Configuration
public class DynamicPropertyFactoryConfig {
    
    
    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void init() {
    
    
        PolledConfigurationSource source = new JDBCConfigurationSource(dataSource,
                "select distinct property_key, property_value from my_site_properties",
                "property_key",
                "property_value");
        //首次任务立即执行,1秒间隔
        FixedDelayPollingScheduler scheduler = new FixedDelayPollingScheduler(0, 1000, false);
        DynamicConfiguration configuration = new DynamicConfiguration(source,
                scheduler);
        ConfigurationManager.install(configuration);
    }
}

4), get the dynamic configuration

@RestController
@RequestMapping("/api/demo1")
public class Demo1Controller {
    
    

    DynamicStringProperty defaultProp = DynamicPropertyFactory.getInstance().getStringProperty(
            "demo", "default");

    @GetMapping
    public String getDynamicStringProperty() {
    
    
        return defaultProp.getValue();
    }
}

Realization effect : request the interface to obtain the dynamic configuration, and the return result is that the property_key in the database is the property_value corresponding to the demo. If you change the value of the database and request the interface again, you can get the latest value.

3. Custom configuration source and polling scheduler

1), custom configuration source

Implement the PolledConfigurationSource interface

public class DynamicConfigurationSource implements PolledConfigurationSource {
    
    
    @Override
    public PollResult poll(boolean initial, Object checkPoint) throws Exception {
    
    
        Map<String, Object> map = new HashMap<>();
        map.put("demo2", UUID.randomUUID().toString());
        return PollResult.createFull(map);
    }
}

If you want to customize the timing scheduler, you can implement the abstract class AbstractPollingScheduler

2), configuration class

@Configuration
public class DynamicPropertyFactoryConfig {
    
    

    @PostConstruct
    public void init() {
    
    
        PolledConfigurationSource source = new DynamicConfigurationSource();
        //首次任务立即执行,1秒间隔 DynamicConfigurationSource中使用UUID 相当于demo2的配置每1秒刷新一次
        FixedDelayPollingScheduler scheduler = new FixedDelayPollingScheduler(0, 1000, false);
        DynamicConfiguration configuration = new DynamicConfiguration(source,
                scheduler);
        ConfigurationManager.install(configuration);
    }
}

3) Get dynamic configuration

@RestController
@RequestMapping("/api/demo2")
public class Demo2Controller {
    
    

    DynamicStringProperty defaultProp = DynamicPropertyFactory.getInstance().getStringProperty(
            "demo2", "default");

    @GetMapping
    public String getDynamicStringProperty() {
    
    
        return defaultProp.getValue();
    }
}

Realization effect : request the interface to obtain dynamic configuration, return the result as UUID, and change every second

reference:

https://blog.csdn.net/yang75108/article/details/86990136

https://github.com/Netflix/archaius/wiki

https://www.cnblogs.com/lexiaofei/p/7169483.html

Guess you like

Origin blog.csdn.net/qq_40378034/article/details/109553007