使用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

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

【北交大信息所AI-Max2】使用方法

BJTU信息所集群AI_MAX2使用方法 使用的前提是预约到相应的算力卡,拥有登录权限的账号密码,一般为导师组共用一个。 有浏览器、ssh工具就可以。 1.新建集群Terminal 浏览器登陆10.126.62.75 (如果是1集群把75改成66) 交互式开发 执行器选Terminal 密码随便设一个(需记住) 工作空间:私有数据、全部文件 加速器选GeForce_RTX_2080_Ti

【Linux 从基础到进阶】Ansible自动化运维工具使用

Ansible自动化运维工具使用 Ansible 是一款开源的自动化运维工具,采用无代理架构(agentless),基于 SSH 连接进行管理,具有简单易用、灵活强大、可扩展性高等特点。它广泛用于服务器管理、应用部署、配置管理等任务。本文将介绍 Ansible 的安装、基本使用方法及一些实际运维场景中的应用,旨在帮助运维人员快速上手并熟练运用 Ansible。 1. Ansible的核心概念