前言
工作项目所负责的模块需要用到货币汇率,本篇仅个人记录。
创建数据库
DROP TABLE IF EXISTS `currency_rate`;
CREATE TABLE `currency_rate` (
`id` bigint(20) NOT NULL COMMENT 'id',
`currency_code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '货币编码',
`currency_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '货币所属国家',
`rate` decimal(24, 6) NULL DEFAULT NULL COMMENT '汇率',
`create_by` bigint(20) NULL DEFAULT NULL COMMENT '创建人',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '货币汇率表' ROW_FORMAT = Dynamic;
创建完数据库可以用自己项目的工具来生成代码,这里我就不贴代码了
业务代码
我的功能不是算钱的仅做校验,不用搞个实时的写个定时任务,每天定时获取一下就行,如果要做实时的建议使用聚合数据 API https://www.juhe.cn/docs/api/id/23 。
我这里用的:中国货币网-中国外汇交易中心主办 (chinamoney.com.cn) get请求方式、返回json类型。
枚举类:
package com.sinosoft.springbootplus.lft.business.common.enums;
import com.sinosoft.springbootplus.mybaitsextend.dict.interfaces.DictEnum;
import java.util.HashMap;
/**
* 币种枚举
*/
public enum CurrencyEnum implements DictEnum {
USD("USD", "美元"),
EUR("EUR", "欧元"),
JPY("JPY", "日元"), // 注意这里特殊处理了JPY
HKD("HKD", "港币"),
GBP("GBP", "英镑"),
AUD("AUD", "澳元"),
NZD("NZD", "新西兰元"),
SGD("SGD", "新加坡元"),
CHF("CHF", "瑞士法郎"),
CAD("CAD", "加元"),
MOP("MOP", "澳门元"),
MYR("MYR", "马来西亚林吉特"),
RUB("RUB", "俄罗斯卢布"),
ZAR("ZAR", "南非兰特"),
KRW("KRW", "韩元"),
AED("AED", "阿联酋迪拉姆"),
SAR("SAR", "沙特里亚尔"),
HUF("HUF", "匈牙利福林"),
PLN("PLN", "波兰兹罗提"),
DKK("DKK", "丹麦克朗"),
SEK("SEK", "瑞典克朗"),
NOK("NOK", "挪威克朗"),
TRY("TRY", "土耳其里拉"),
MXN("MXN", "墨西哥比索"),
THB("THB", "泰铢"),
CNY("CNY", "人民币");
private final String value;
private final String label;
CurrencyEnum(String value, String label) {
this.value = value;
this.label = label;
}
private static HashMap<String, CurrencyEnum> data = new HashMap<>();
static {
for (CurrencyEnum currencyEnum : CurrencyEnum.values()) {
data.put(currencyEnum.getValue(), currencyEnum);
}
}
public static CurrencyEnum parse(String code) {
if (data.containsKey(code)) {
return data.get(code);
}
return null;
}
@Override
public String getValue() {
return this.value;
}
@Override
public String getlable() {
return this.label;
}
@Override
public String getDictName() {
return "币种";
}
@Override
public String getDictDesc() {
return "币种";
}
}
application.yml
#货币汇率
hl:
# 货币汇率接口地址
url: https://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew
CurrencyRateConfig
package com.sinosoft.springbootplus.lft.business.dispatch.tourbank.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 货币汇率
*
* @author gj
*/
@Configuration
@ConfigurationProperties(
prefix = "hl"
)
@Data
public class CurrencyRateConfig {
private String url;
}
定时任务方法:
@Transactional(rollbackFor = Exception.class)
public void pullCurrencyRate(String text) throws Exception {
log.info("开始获取货币汇率");
//?startDate=2024-07-19&endDate=2024-07-19&pageNum=1&pageSize=30
//String s = "https://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew";
String today = DateUtil.today();
Map<String, Object> query = new HashMap<>(4);
query.put("startDate", today);
query.put("endDate", today);
query.put("pageNum", "1");
query.put("pageSize", "30");
String response = OkHttpRequestUtils.doGet(currencyRateConfig.getUrl(), query);
log.info("获取货币汇率返回结果:{}", response);
CurrencyRateVo currencyRateVo = JSONObject.parseObject(response, CurrencyRateVo.class);
List<CurrencyRateData> data = currencyRateVo.getData();
if (data.get(0).getTotal() > 0) {
//获取货币名称
List<String> searchlist = data.get(0).getSearchlist();
//货币汇率
List<String> values = currencyRateVo.getRecords().get(0).getValues();
List<CurrencyRate> currencyRateList = new ArrayList<>();
CurrencyEnum[] enums = CurrencyEnum.values();
//存入表中
for (int i = 0; i <25; i++) {
//货币名称
String currencyName = searchlist.get(i);
String rate = values.get(i);
CurrencyRate currency = new CurrencyRate();
currency.setCurrencyName(enums[i].getlable())
.setCurrencyCode(enums[i].getValue());
if (StringUtils.contains(currencyName, CurrencyEnum.USD.getValue())
||StringUtils.contains(currencyName, CurrencyEnum.EUR.getValue())
||StringUtils.contains(currencyName, CurrencyEnum.HKD.getValue())
||StringUtils.contains(currencyName, CurrencyEnum.GBP.getValue())
||StringUtils.contains(currencyName, CurrencyEnum.AUD.getValue())
||StringUtils.contains(currencyName, CurrencyEnum.NZD.getValue())
||StringUtils.contains(currencyName, CurrencyEnum.SGD.getValue())
||StringUtils.contains(currencyName, CurrencyEnum.CHF.getValue())
||StringUtils.contains(currencyName, CurrencyEnum.CAD.getValue())){
currency.setRate(new BigDecimal(rate));
} else if (StringUtils.contains(currencyName, CurrencyEnum.JPY.getValue())) {
//日元
currency.setRate(new BigDecimal(rate).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
} else {
currency.setRate(BigDecimal.ONE.divide(new BigDecimal(rate), 2, RoundingMode.HALF_UP));
}
currencyRateList.add(currency);
}
//删除数据
currencyRateDomain.deleteAll();
//存入数据
mybatisBatchUtils.saveBatch(CurrencyRateMapper.class,CurrencyRate.class,currencyRateList);
}
log.info(currencyRateVo.toString());
}