Dayu Multilingual Support Component

background
Based on customer demand, some international delivery projects need to achieve front-end page, pop-up window multilingual implementation. With the increase of delivery projects, projects with this requirement are also growing. For Java language, multilingual implementation is basically the same, so a unified implementation is required.
major function
The internationalization of "static" content, including exception information, prompt information, front-end display content, such as menu configuration, permission configuration, etc.
The internationalization of "dynamic" content, including user input, can dynamically add/modify content, such as the name of government departments, street addresses, etc.

The internationalization of "nacos" content. The internationalization scheme of such content tries out the dynamic registration of nacos, which can take effect in real time by modifying nacos.

springboot-demo Download
📎i18n-sample-app.zip
📎i18n-sample-app_v1.0.1.zip
Docking guidance
1.1 setting.xml
📎settings_bpaas.xml
1.2 pom.xml
1. Introduce maven coordinates: (2021-9-7 cutoff, aliyun-gts-starter-i18n latest version 1.0.5-SNAPSHOT)

(2) Project Root Catalog Introduction

    <dependencyManagement>    
        <dependency>
            <groupId>com.aliyun.gts.bpaas</groupId>
            <artifactId>aliyun-gts-starter-i18n</artifactId>
            <version>1.0.5-SNAPSHOT</version>
        </dependency>
    </dependencyManagement>

Then add the following dependencies to the module dependencies used.

    <dependency>
        <groupId>com.aliyun.gts.bpaas</groupId>
        <artifactId>aliyun-gts-starter-i18n</artifactId>
    </dependency>

1.3 Profile Configuration

server:
  servlet:
    context-path: /i18nTest
spring:
  application:
    name: aliyun-gts-starter-i18n-test
  # Configuration of Spring Message, which must be configured with bundle-resource
  messages:
    basename: i18n/messages
    encoding: UTF-8
    fallbackToSystemLocale: false

gts:
  i18n:
    nacos-resource:
      // Whether to automatically assemble nacosResource Bean
      enable: true
      serverAddress: XXX
      username: XXX
      password: XXXX
      dataId: XXXX
      group: XXXXX
    memory-resource:
		  // Whether to automatically assemble memoryResource Bean
      enable: true
      #Generate Internationalized Identity Key
      key-generator:
        namespace: TFYYIOUJBHGHUBDABBDKJLKJB
        default-code: code
        delimiter: ^
    bundle-resource:
      enable: true
    web:
      code-field-name: code
      message-field-name: message
      view-object-class-name: com.aliyun.gts.bpass.i18n.support.protocol.JsonProtocol
  cache:
    type: redis
    prefix:
    host: XXXX
    port: XXXX
    auth: XXXX
    database: XXXX

SDK and API
introduce
There are currently three types of adapters, BundleAdapter, memoryAdapter, and nacosAdapter.
BundleAdapter
API List

/**
     * Acquiring international resources through resource key and language
     * @param key Resource key
     * @param locale language information
     * @return Internationalized string
     */
    String getString(String key, Locale locale);

    /**
     * Getting international resources through code identity and unique id
     * @see com.aliyun.gts.bpass.i18n.key.KeyGenerator
     * @param code code Identification
     * @param id Unique Primary Key
     * @param locale language information
     * @return Internationalized Resources
     */
    String getStringWithCode(String code, String id, Locale locale);

    /**
     * Getting international resources through default code identity and unique id
     * @see com.aliyun.gts.bpass.i18n.key.KeyGenerator
     * @param id Unique Primary Key
     * @param locale language information
     * @return Internationalized Resources
     */
    default String getStringWithId(String id, Locale locale) {
        return getStringWithCode(null, id, locale);
    }

Try demo
1. You can first create i18n-related resources under the project's static file as shown in the diagram

2. Set the language of the browser, for example, Google

3. Languages are acquired from the browser's Acept-Language

4. You can also set the default language based on the following configuration. If there is no browser-selected language in the messages configuration, the default configuration language will be tried.

i18n.setDefaultLocale(new Locale("zh", "TW"));

5.api calls

@Resource
private BundleResource i18n;

public ResultResponse testGetStringForThrow(){
                //Set Error Throwing Exception Information
        i18n.setThrowExceptionIfNotExists(true);
        Get translations based on the browser's current language
        String string = i18n.getString(key, I18nUtils.getCurrentLanguage());
        String string1 = i18n.getStringWithCode(code,id,I18nUtils.getCurrentLanguage());
        String string2 = i18n.getStringWithId(id,I18nUtils.getCurrentLanguage());
        return ResultResponse.succResult(string);
}



Effect demonstration
1. Set the browser to Chinese (simplified)


memoryAdapter
API List

/**
     * Acquiring international resources through resource key and language
     * @param key Resource key
     * @param locale language information
     * @return Internationalized string
     */
    String getString(String key, Locale locale);

    /**
     * Getting international resources through code identity and unique id
     * @see com.aliyun.gts.bpass.i18n.key.KeyGenerator
     * @param code code Identification
     * @param id Unique Primary Key
     * @param locale language information
     * @return Internationalized Resources
     */
    String getStringWithCode(String code, String id, Locale locale);

    /**
     * Getting international resources through default code identity and unique id
     * @see com.aliyun.gts.bpass.i18n.key.KeyGenerator
     * @param id Unique Primary Key
     * @param locale language information
     * @return Internationalized Resources
     */
    default String getStringWithId(String id, Locale locale) {
        return getStringWithCode(null, id, locale);
    }
/**
     * Set up international resources
     * @param key Resource key
     * @param value Values for corresponding languages
     * @param locale language information
     */
    void setString(String key, String value, Locale locale);

    /**
     *
     * Update/write nationalized resources through code identity
     * @param code code Identification
     * @param id Unique Primary Key
     * @param locale language information
     */
    void setStringWithCode(String code, String id, String value, Locale locale);

    /**
     *
     * Update/write nationalized resources by default code identity
     * @param id Unique Primary Key
     * @param locale language information
     */
    default void setStringWithId(String id, String value, Locale locale) {
        setStringWithCode(null, id, value, locale);
    }

Try demo
1. Set the language of the browser, for example, Google

2. Language is acquired from the browser's Acept-Language

3. If you want to use the middleware cacheManager

Documentation can be used to refer to dependencies and related configurations that introduce cacheManager into docking projects
https://dayu.work/devops/materiel/component?sceneId=2001&classificationId=2102&comId=3210

If you don't use cacheManager, you go to local memory.
Note: Local memory is not recommended for multi-machine deployments.

4.api calls

    @Resource
    private MemoryResource i18n;

    
    public ResultResponse testGetStringForThrow(String key){
            i18n.setThrowExceptionIfNotExists(true);
        String string = i18n.getString(key, I18nUtils.getCurrentLanguage());
    
    }
    
    
    public void testMemorySetStringWithCode( UserEntity userEntity){
        i18n.setThrowExceptionIfNotExists(true);
        i18n.setDefaultLocale(I18nUtils.getCurrentLanguage());
        List<KeyValuePair> pairs = extractor.extract("userName", userEntity);
        for (KeyValuePair p : pairs) {
            i18n.setStringWithCode(USER_NAME_CODE, userEntity.getUserCode(), p.getValue(), p.getLocale());
        }
    }

    public ResultResponse testMemoryGetStringWithCode( String userCode){
        i18n.setThrowExceptionIfNotExists(true);
        i18n.setDefaultLocale(new Locale("zh", "TW"));
        String stringWithCode = i18n.getStringWithCode(USER_NAME_CODE, userCode, I18nUtils.getCurrentLanguage());
        return ResultResponse.succResult(stringWithCode);
    }

Effect demonstration
1. Multiple languages can be set dynamically and interfaces can be invoked
http://localhost:8080/i18nTest/memory/testMemorySetStringWithCode


nacosAdapter
API List

/**
     * Acquiring international resources through resource key and language
     * @param key Resource key
     * @param locale language information
     * @return Internationalized string
     */
    String getString(String key, Locale locale);

    /**
     * Getting international resources through code identity and unique id
     * @see com.aliyun.gts.bpass.i18n.key.KeyGenerator
     * @param code code Identification
     * @param id Unique Primary Key
     * @param locale language information
     * @return Internationalized Resources
     */
    String getStringWithCode(String code, String id, Locale locale);

    /**
     * Getting international resources through default code identity and unique id
     * @see com.aliyun.gts.bpass.i18n.key.KeyGenerator
     * @param id Unique Primary Key
     * @param locale language information
     * @return Internationalized Resources
     */
    default String getStringWithId(String id, Locale locale) {
        return getStringWithCode(null, id, locale);
    }

Try demo
1. You first need to configure the relevant configuration in the nacos registry

2. Set the language of the browser, for example, Google

3. Languages are acquired from the browser's Acept-Language

4. You can also set the default language based on the following configuration. If there is no browser-selected language in the messages configuration, the default configuration language will be tried.

i18n.setDefaultLocale(new Locale("zh", "TW"));

5.api calls

@Resource
private NacosResource i18n;

public ResultResponse testGetStringForThrow(){
                //Set Error Throwing Exception Information
        i18n.setThrowExceptionIfNotExists(true);
        Get translations based on the browser's current language
        String string = i18n.getString(key, I18nUtils.getCurrentLanguage());
        String string1 = i18n.getStringWithCode(code,id,I18nUtils.getCurrentLanguage());
        String string2 = i18n.getStringWithId(id,I18nUtils.getCurrentLanguage());
        return ResultResponse.succResult(string);
}



Effect demonstration
1. Set the browser to Chinese (simplified)

2. Start the springboot-demo project provided above to access the interface
http://localhost:8080/i18nTest/nacos/testGetStringForThrow?key=country

Tags: Java

Posted on Sat, 18 Sep 2021 18:18:11 -0400 by web_loone_08