使用dropwizard(6)-国际化-easy-i18n

2024-05-03 09:58

本文主要是介绍使用dropwizard(6)-国际化-easy-i18n,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


前言

Dropwizard官方文档并没有提供国际化的模块,所以只能自己加。Spring的MessageResource用的很顺手,所以copy过来。

作者:@Ryan-Miao
本文为作者原创,转载请注明出处:http://www.cnblogs.com/woshimrf/p/dropwizard-i18n.html

Easy i18n

在整合Dropwizard的时候,多语言貌似只能通过jdk自带的ResourceBundle拿数据。其实也就够了,但在开发过程中发现需要缓存,需要解析占位符等。代码越写越多,显然不是仅仅一个调用就完事的。写的差不多的时候突然觉得和spring context里的message source结构类似。于是,放弃维护已经开始变的复杂的逻辑,直接使用spring。

但选取dropwizard的时候就是摒弃了spring,再拿过来也不好玩了。干脆,抽取Spring context项目的MessageResource相关代码,重写封装了一个library: https://github.com/Ryan-Miao/easy-i18n, 欢迎star。

easy-i18n还是和在Spring项目中相同。

首先,引入依赖,由于github项目的library已经有仓库去维护了,就没费心思放到maven和jcenter了,直接从github上拉取。类库地址为:

<repositories><repository><id>jitpack.io</id><url>https://jitpack.io</url></repository>
</repositories>

引入

<dependency><groupId>com.github.Ryan-Miao</groupId><artifactId>easy-i18n</artifactId><version>1.0</version>
</dependency>

简单使用

#情形一 只有一个Resource Bundle

在resources下新建i18n/messages.properties以及i18n/messages_zh_CN.properties. demo位置:l4dropwizard

然后,调用方法如下:

@Test
public void testI18n(){ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.addBasenames("i18n/messages");messageSource.setDefaultEncoding("UTF-8");String index = messageSource.getMessage("index", null, Locale.US);System.out.println(index);
}

#情形二 我有多个Resource Bundle

实际项目中,由于产品分类,有时候需要创建多个Resource Bundle,这时候也简单,只要创建多个ResourceBundleMessageSource来读取翻译即可。


public void testI18n2(){ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.addBasenames("i18n/messages");messageSource.setDefaultEncoding("UTF-8");String index = messageSource.getMessage("index", null, Locale.US);System.out.println(index);ResourceBundleMessageSource messageSource2 = new ResourceBundleMessageSource();messageSource2.addBasenames("i18n/messages2");messageSource2.setDefaultEncoding("UTF-8");String second = messageSource2.getMessage("second", null, Locale.US);System.out.println(second);
}

#情形三 我有多个Resource Bundle但读取翻译的时候我想一起

有时候,想要读取翻译,可能翻译文件在不同的Resource Bundle,但我指向用一个接口去调用。这时候,做法时候在这几个Resource Bundle的里面添加命名空间,即key要在这几个Resource Bundle里唯一,而不仅仅是本文件唯一。

然后,


public void testI18n2(){ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.addBasenames("i18n/messages", "i18n/messages2");messageSource.setDefaultEncoding("UTF-8");String index = messageSource.getMessage("index", null, Locale.US);System.out.println(index);
}

这种做法,会一次从两个Resource Bundle里寻找翻译,找到即返回。因此,如果有相同的key,将导致只有第一个生效。

#情形4

没有了,你翻译要那么复杂吗。

更多用法,参考测试类:ResourceBundleMessageSourceTest

Demo source

https://github.com/Ryan-Miao/l4dropwizard

本文是基于dropwizard入门之上的演进。

确保依赖都是最新的,或者自行解决版本冲突,比如jackson不同版本之间的类有所不同。

引入easy-i18n

repository url

<repositories><repository><id>jitpack.io</id><url>https://jitpack.io</url></repository>
</repositories>

引入

<dependency><groupId>com.github.Ryan-Miao</groupId><artifactId>easy-i18n</artifactId><version>1.0</version>
</dependency>

添加Resource Bundle

在resources下新增文件夹i18n, 依次添加几个Resource Bundle。具体做法是,在文件夹i18n右键 -> new -> Resource Bundle, 然后选择想要支持的语言。比如美国en_US,简体中文zh_CN

新建MessageService

创建一个Util来处理翻译功能。
com.test.domain.service.IMessageService

package com.test.domain.service;import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;/*** The Message translation service* Created by Ryan Miao on 11/23/17.*/
public interface IMessageService {/*** Get translation by message key.** @param key The message key in the properties* @return the translated message*/String getMessage(String key, Locale locale);/*** Get translation by message key and compose it with variables.* Note that the variable would be injected by {@link MessageFormat}** @param key The message key in the properties* @param args The variables to inject into the message.* @return the translated message.*/String getMessage(String key, List<String> args, Locale locale);
}

实现类com.test.domain.service.impl.MessageService

package com.test.domain.service.impl;import com.miao.easyi18n.support.ResourceBundleMessageSource;
import com.test.domain.service.IMessageService;import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.Locale;/*** Created by Ryan Miao on 11/23/17.*/
@Singleton
public class MessageService implements IMessageService{private final ResourceBundleMessageSource messageSource;@Injectpublic MessageService(ResourceBundleMessageSource messageSource) {this.messageSource = messageSource;}@Overridepublic String getMessage(String key, Locale locale) {return messageSource.getMessage(key, null, locale);}@Overridepublic String getMessage(String key, List<String> args, Locale locale) {return messageSource.getMessage(key, args.toArray(), locale);}
}

在IoC中提供ResourceBundleMessageSource

由于ResourceBundleMessageSource是公共组件,需要单独提取出来,并使用单例模式创建。关于IoC的配置,参阅dropwizard中添加DI

ConfigurationModule中:

package com.test.domain.ioc.module;import com.miao.easyi18n.support.ResourceBundleMessageSource;
import com.test.configuration.HelloWorldConfiguration;
import dagger.Module;
import dagger.Provides;import javax.inject.Singleton;/*** Created by Ryan Miao on 11/20/17.*/
@Module
public class ConfigurationModule {private final HelloWorldConfiguration configuration;public ConfigurationModule(HelloWorldConfiguration configuration) {this.configuration = configuration;}@Provides@SingletonHelloWorldConfiguration helloWorldConfiguration(){return configuration;}@Singleton@ProvidesResourceBundleMessageSource resourceBundleMessageSource(){ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();messageSource.addBasenames("i18n/messages", "i18n/messages2", "i18n/otherGroup");messageSource.setDefaultEncoding("UTF-8");return messageSource;}
}

这里,关于Resource Bundle的位置没有单独提出来,后面可以放到HelloWorldConfiguration,提到配置文件中。

测试

在dagger中,接口和实现类的绑定只能通过手动声明。因此,绑定IMessageService

@Singleton
@Provides
IMessageService messageService(MessageService messageService){return messageService;
}

创建测试Resource, com.test.domain.resource.LocalResource

package com.test.domain.resource;import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableMap;
import com.test.domain.entiry.GithubUser;
import com.test.domain.service.IMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Locale;
import java.util.Map;/*** Test localization* Created by Ryan Miao on 11/23/17.*/
@Api("/local")
@Path("/local")
@Produces(MediaType.APPLICATION_JSON)
public class LocalResource {private final IMessageService messageService;@Injectpublic LocalResource(IMessageService messageService) {this.messageService = messageService;}@GET@Timed@Path("/{key}")@ApiOperation(value = "Get github user profile.", notes = "There should be the note.")@ApiResponses({@ApiResponse(code = 401, message = "Valid credentials are required to access this resource."),@ApiResponse(code = 400, message = "Params not valid."),@ApiResponse(code = 500, message = "Something wrong from the server."),@ApiResponse(code = 200, message = "Success.", response = GithubUser.class)})public Map<String, String> getIndex(@PathParam("key") final String index,@HeaderParam("Accept-Language") @Valid@NotNull(message = "cannot be null.")@Pattern(regexp = "([a-z]{2}-[A-Z]{2})", message = "pattern should like zh-CN, en-US.")final String language) {final Locale locale = Locale.forLanguageTag(language);final String message = messageService.getMessage(index, locale);return ImmutableMap.of(index, message);}
}

结果

这篇关于使用dropwizard(6)-国际化-easy-i18n的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/956469

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud