Study hard, may still do not understand; Don’t study hard, don’t even understand the opportunity to have no, you fine.

1. Introduction

Recently in the MySQL lock related part of the knowledge, this plan to write an article, good to their own understanding of the things recorded, but also hope to spread to the boy in need. But, the content is too complex, in the realm of half-understanding, so give up the relevant writing, so as not to mislead everyone (although not too many people see, hey hey hey).

Don’t write MySQL, write distributed services essential artifact configuration center, it isn’t fragrant?

In daily development, I believe you are familiar with database configuration, MQ configuration, Redis configuration, switch configuration and other configurations. Compared with database configuration, MQ configuration, Redis configuration these static configurations, switch configuration belongs to dynamic configuration, and may often need to be turned on and off.

I will take you to review the painful experience: the product manager found you, smiled happily and said to you: “Xiao Wang help to open the configuration switch, business needs”, Xiao Wang happily agreed, don’t modify a switch configuration? I’ll do it in a minute. I’ll show you the real thing. So, Wang modified the configuration, released the application online, and then happily began to write daily bugs. Suddenly, a familiar voice came to my ears: “Help Wang to close the configuration switch, the business said that it does not need this function”, Xiao Wang’s heart: “I XXX, this change demand faster than face?” Even though he was upset, Wang had to modify the configuration and re-publish the app for the sake of the happiness of his neighbor.

Unwilling to be tortured by the product manager, Wang remembered his friend next door. After a fierce discussion with his friend next door, Wang remembered a key word Apollo and started his learning journey.

2. Apollo is introduced

Apollo is a distributed configuration center developed by the Framework department of Ctrip. It can centrally manage configurations in different environments and clusters, and push configurations to applications in real time after modification. It has standardized permissions and process governance features, and is suitable for micro-service configuration management scenarios.

2.1 Apollo Core Concepts

  • Applications: projects developed by developers
  • Environment: Application deployment environment, such as development environment, test environment, acceptance environment, and online environment
  • Cluster: Application clusters deployed for different data centers in each environment
  • Namespace: a configuration file used to classify configurations. For example, Redis configuration, database configuration, and Kafka configuration can be stored in different namespaces

2.2 Apollo architecture


The following roles can be seen from the architecture diagram above:

  • Config service: used to read and push configurations. The service object is Apollo client
  • Admin service: used to modify and publish configurations. The service object is portal
  • Portal: Apollo Provides a configuration interface for users
  • Client: used to pull configuration information from the Config Service
  • Eureka: For registration and discovery of services
  • Meta Server: Encapsulates service discovery logic

2.3 Apollo Core process

  • The config service and admin service register services with eureka

  • The client and portal use meta to discover services

  • Users can add or modify configurations on the Portal

  • The user clicks config Publish and invokes the admin Service through the interface

  • The admin service saves the configuration changes and inserts the change information into the table

  • Config Service Scans the table for the latest configuration changes and pushes the changes to the client

  • The client periodically pulls the latest configuration information from the Config Service

    As described above, we need to deploy the Apollo service and build our own client

3. Environment construction

The environment construction process can refer to the official website for details. There was an introduction of the environment construction process, but it had to be deleted due to the word limit.

After setting up the environment, enter //localhost:8070 in the browser. Use the user name Apollo and password admin to log in. The following interface is displayed

4. The real

4.1 Creating a Project on the Portal

The application name of the project is boot-example- Apollo, and the corresponding appID is boot-example- Apollo

⚠️ The appID specified when creating the project must be the same as the AppID in the client project configuration file; otherwise, configuration information cannot be correctly read

4.2 Adding Configurations

First click on the one on the rightAdd configuration buttonWhen you save, be sure to clickrelease

4.3 Creating a Client Project

This will add pom

<dependencies>
    <dependency>
        <groupId>com.ctrip.framework.apollo</groupId>
        <artifactId>apollo-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>
Copy the code

4.3.2 Adding Aollo Configurations

server:

port: 8081

app:

id: boot-example-apollo # specify the appID of the application when the browser creates the project

apollo:

bootstrap:

enabled: true Inject the application namespace at startup

meta: http://localhost:8080 Specify the address of the meta service

cacheDir: /Users/pengli/software/idea/workspace/data/apollo-config-cache # localcache file address

Copy the code

4.3.3 Creating an Entity Class

@Data

@ToString

@Component

public class TestJavaConfigBean {



    @Value("${timeout:100}")

    private int timeout;



    @Value("${batch:200}")

    private int batch;

}

Copy the code

4.3.4 Creating a startup Class

@SpringBootApplication

@EnableApolloConfig

public class ApolloApplication {



    private static TestJavaConfigBean testJavaConfigBean;



    @Autowired

    public void setTestJavaConfigBean(TestJavaConfigBean testJavaConfigBean) {

        ApolloApplication.testJavaConfigBean = testJavaConfigBean;

    }



    public static void main(String[] args) {

        SpringApplication.run(ApolloApplication.class, args);



        System.out.println("TestJavaConfigBean======>" + testJavaConfigBean);

    }

}

Copy the code

4.3.5 Starting the Project

After starting the project, you should see the following print:

TestJavaConfigBean======>TestJavaConfigBean(timeout=500, batch=300)

Copy the code

4.3.6 Viewing Local Cache Files

cat boot-example-apollo+default+application.properties

#Persisted by DefaultConfig

#Tue Feb 25 16:22:49 CST 2020

batch=300

timeout=500

Copy the code

This shows that Apollo essentially caches our configuration information to ensure that it can still be read if the service is unavailable

4.4 Inject the configuration as @configurationProperties

4.4.1 Creating an Entity Class

@ConfigurationProperties(prefix = "redis.cache")

@Component

@Data

@ToString

public class SampleRedisConfig {

    private int expireSeconds;

    private int commandTimeout;

}

Copy the code

4.4.2 Modifying a Configuration Class

@Configuration

@EnableConfigurationProperties(value = SampleRedisConfig.class)

public class AppConfig {



    @Bean

    public TestJavaConfigBean testJavaConfigBean(a) {

        return new TestJavaConfigBean();

    }

}

Copy the code

4.4.3 Adding Related configurations on Apollo


4.4.4 Run the program

SampleRedisConfig======>SampleRedisConfig(expireSeconds=1000, commandTimeout=2000)

Copy the code

You can see that this method can also read the corresponding configuration information. In this case, you can try modifying the configuration on Portal to see if your application can read the latest configuration. After testing, you will find that the client cannot read the latest configuration. In this case, you need to implement the automatic refresh function so that the client can read the latest configuration properties.

4.5 About @ConfigurationProperties Automatic refresh

4.5.1 Add the @refreshScope annotation to the Entity class

@ConfigurationProperties(prefix = "redis.cache")

@Component

@RefreshScope

@Data

@ToString

public class SampleRedisConfig {

    private int expireSeconds;

    private int commandTimeout;

}

Copy the code

4.5.2 Creating an Automatic Refresh Configuration Class

@Component

@Slf4j

public class AppRefreshConfig {



    @Autowired

    private RefreshScope refreshScope;



    @Autowired

    private SampleRedisConfig sampleRedisConfig;



    @ApolloConfigChangeListener

    public void onChange(ConfigChangeEvent changeEvent) {

        log.info("before refresh {}", sampleRedisConfig.toString());

        refreshScope.refresh("sampleRedisConfig");

        log.info("after refresh {}", sampleRedisConfig.toString());

    }

}

Copy the code

4.6 Reading Non-default Namespace Configurations

4.6.1 Creating a Namespace

Create a namespace named dataSource on the Apollo service

4.6.2 Modifying a Configuration File

server:

port: 8081

app:

id: boot-example-apollo # specify the appID of the application when the browser creates the project

apollo:

bootstrap:

enabled: true Inject the application namespace at startup

namespaces: application,order-service.dataSource

meta: http://localhost:8080 Specify the address of the meta service

cacheDir: /Users/pengli/software/idea/workspace/data/apollo-config-cache # localcache file address

Copy the code

Note: Apollo. The bootstrap. Enabled = true and Apollo bootstrap. Namespaces = application, order – service. The dataSource that two configuration must exist at the same time, the source code analysis is as follows:


4.6.3 Creating an Entity Class

@Component

@Data

@ToString

public class DatasourceConfig {



    @Value("${spring.datasource.url:''}")

    private String url;



    @Value("${spring.datasource.username:''}")

    private String userName;



    @Value("${spring.datasource.password:''}")

    private String password;

}

Copy the code

4.6.4 Running the project

DatasourceConfig = = = = = = > DatasourceConfig (= JDBC url: mysql: / / 127.0.0.1:3306 /test? useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true, userName=root, password=root)

Copy the code

5. Conclusion

At this point, although Xiao Wang had become Lao Wang, he was secretly pleased: “From now on, there is no need to worry about the product manager’s need to modify the configuration, you change your change, my heart will soar.”

This is the end of the sharing, you can refer to boot-example-Apollo for the corresponding project code, for any questions or questions, feel free to leave a comment section, looking forward to seeing you next time.