Merge branch 'master' of https://gitee.com/zhijiantianya/ruoyi-vue-pro into feature/mall_product

# Conflicts:
#	yudao-framework/yudao-spring-boot-starter-web/src/main/java/cn/iocoder/yudao/framework/jackson/config/YudaoJacksonAutoConfiguration.java
#	yudao-module-mall/yudao-module-promotion-api/src/main/java/cn/iocoder/yudao/module/promotion/enums/ErrorCodeConstants.java
#	yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/controller/app/bargain/vo/activity/AppBargainActivityDetailRespVO.java
#	yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/controller/app/bargain/vo/activity/AppBargainActivityRespVO.java
#	yudao-module-mall/yudao-module-trade-api/src/main/java/cn/iocoder/yudao/module/trade/enums/ErrorCodeConstants.java
#	yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/order/vo/AppTradeOrderSettlementReqVO.java
#	yudao-module-member/yudao-module-member-api/src/main/java/cn/iocoder/yudao/module/member/enums/ErrorCodeConstants.java
#	yudao-module-pay/yudao-module-pay-api/src/main/java/cn/iocoder/yudao/module/pay/enums/ErrorCodeConstants.java
#	yudao-server/src/main/resources/application-local.yaml
This commit is contained in:
YunaiV
2023-09-28 15:18:59 +08:00
575 changed files with 1987 additions and 47700 deletions

View File

@@ -6,9 +6,6 @@ import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.config.FileConfigPageReqVO;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileConfigDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.time.LocalDateTime;
@Mapper
public interface FileConfigMapper extends BaseMapperX<FileConfigDO> {
@@ -21,7 +18,8 @@ public interface FileConfigMapper extends BaseMapperX<FileConfigDO> {
.orderByDesc(FileConfigDO::getId));
}
@Select("SELECT COUNT(*) FROM infra_file_config WHERE update_time > #{maxUpdateTime}")
Long selectCountByUpdateTimeGt(LocalDateTime maxUpdateTime);
default FileConfigDO selectByMaster() {
return selectOne(FileConfigDO::getMaster, true);
}
}

View File

@@ -1,10 +1,8 @@
package cn.iocoder.yudao.module.infra.service.file;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.file.core.client.FileClient;
@@ -17,22 +15,22 @@ import cn.iocoder.yudao.module.infra.controller.admin.file.vo.config.FileConfigU
import cn.iocoder.yudao.module.infra.convert.file.FileConfigConvert;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileConfigDO;
import cn.iocoder.yudao.module.infra.dal.mysql.file.FileConfigMapper;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.validation.Validator;
import java.time.LocalDateTime;
import java.util.List;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.Objects;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.cache.CacheUtils.buildAsyncReloadingCache;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_CONFIG_DELETE_FAIL_MASTER;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_CONFIG_NOT_EXISTS;
@@ -46,19 +44,29 @@ import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.FILE_CONFIG
@Slf4j
public class FileConfigServiceImpl implements FileConfigService {
@Resource
private FileClientFactory fileClientFactory;
private static final Long CACHE_MASTER_ID = 0L;
/**
* 文件配置的缓存
* {@link FileClient} 缓存,通过它异步刷新 fileClientFactory
*/
@Getter
private List<FileConfigDO> fileConfigCache;
/**
* Master FileClient 对象,有且仅有一个,即 {@link FileConfigDO#getMaster()} 对应的
*/
@Getter
private FileClient masterFileClient;
private final LoadingCache<Long, FileClient> clientCache = buildAsyncReloadingCache(Duration.ofSeconds(10L),
new CacheLoader<Long, FileClient>() {
@Override
public FileClient load(Long id) {
FileConfigDO config = Objects.equals(CACHE_MASTER_ID, id) ?
fileConfigMapper.selectByMaster() : fileConfigMapper.selectById(id);
if (config != null) {
fileClientFactory.createOrUpdateFileClient(id, config.getStorage(), config.getConfig());
}
return fileClientFactory.getFileClient(id);
}
});
@Resource
private FileClientFactory fileClientFactory;
@Resource
private FileConfigMapper fileConfigMapper;
@@ -66,53 +74,12 @@ public class FileConfigServiceImpl implements FileConfigService {
@Resource
private Validator validator;
@PostConstruct
public void initLocalCache() {
// 第一步:查询数据
List<FileConfigDO> configs = fileConfigMapper.selectList();
log.info("[initLocalCache][缓存文件配置,数量为:{}]", configs.size());
// 第二步:构建缓存:创建或更新文件 Client
configs.forEach(config -> {
fileClientFactory.createOrUpdateFileClient(config.getId(), config.getStorage(), config.getConfig());
// 如果是 master进行设置
if (Boolean.TRUE.equals(config.getMaster())) {
masterFileClient = fileClientFactory.getFileClient(config.getId());
}
});
this.fileConfigCache = configs;
}
/**
* 通过定时任务轮询,刷新缓存
*
* 目的:多节点部署时,通过轮询”通知“所有节点,进行刷新
*/
@Scheduled(initialDelay = 60, fixedRate = 60, timeUnit = TimeUnit.SECONDS)
public void refreshLocalCache() {
// 情况一:如果缓存里没有数据,则直接刷新缓存
if (CollUtil.isEmpty(fileConfigCache)) {
initLocalCache();
return;
}
// 情况二,如果缓存里数据,则通过 updateTime 判断是否有数据变更,有变更则刷新缓存
LocalDateTime maxTime = CollectionUtils.getMaxValue(fileConfigCache, FileConfigDO::getUpdateTime);
if (fileConfigMapper.selectCountByUpdateTimeGt(maxTime) > 0) {
initLocalCache();
}
}
@Override
public Long createFileConfig(FileConfigCreateReqVO createReqVO) {
// 插入
FileConfigDO fileConfig = FileConfigConvert.INSTANCE.convert(createReqVO)
.setConfig(parseClientConfig(createReqVO.getStorage(), createReqVO.getConfig()))
.setMaster(false); // 默认非 master
fileConfigMapper.insert(fileConfig);
// 刷新缓存
initLocalCache();
return fileConfig.getId();
}
@@ -125,8 +92,8 @@ public class FileConfigServiceImpl implements FileConfigService {
.setConfig(parseClientConfig(config.getStorage(), updateReqVO.getConfig()));
fileConfigMapper.updateById(updateObj);
// 刷新缓存
initLocalCache();
// 清空缓存
clearCache(config.getId(), null);
}
@Override
@@ -139,8 +106,8 @@ public class FileConfigServiceImpl implements FileConfigService {
// 更新
fileConfigMapper.updateById(new FileConfigDO().setId(id).setMaster(true));
// 刷新缓存
initLocalCache();
// 清空缓存
clearCache(null, true);
}
private FileClientConfig parseClientConfig(Integer storage, Map<String, Object> config) {
@@ -164,8 +131,23 @@ public class FileConfigServiceImpl implements FileConfigService {
// 删除
fileConfigMapper.deleteById(id);
// 刷新缓存
initLocalCache();
// 清空缓存
clearCache(id, null);
}
/**
* 清空指定文件配置
*
* @param id 配置编号
* @param master 是否主配置
*/
private void clearCache(Long id, Boolean master) {
if (id != null) {
clientCache.invalidate(id);
}
if (Boolean.TRUE.equals(master)) {
clientCache.invalidate(CACHE_MASTER_ID);
}
}
private FileConfigDO validateFileConfigExists(Long id) {
@@ -192,12 +174,17 @@ public class FileConfigServiceImpl implements FileConfigService {
validateFileConfigExists(id);
// 上传文件
byte[] content = ResourceUtil.readBytes("file/erweima.jpg");
return fileClientFactory.getFileClient(id).upload(content, IdUtil.fastSimpleUUID() + ".jpg", "image/jpeg");
return getFileClient(id).upload(content, IdUtil.fastSimpleUUID() + ".jpg", "image/jpeg");
}
@Override
public FileClient getFileClient(Long id) {
return fileClientFactory.getFileClient(id);
return clientCache.getUnchecked(id);
}
@Override
public FileClient getMasterFileClient() {
return clientCache.getUnchecked(CACHE_MASTER_ID);
}
}

View File

@@ -3,27 +3,27 @@ import { defHttp } from '@/utils/http/axios'
// 查询${table.classComment}列表
export function get${simpleClassName}Page(params) {
return defHttp.get({ url: '${baseURL}/page', params })
return defHttp.get({ url: '${baseURL}/page', params })
}
// 查询${table.classComment}详情
export function get${simpleClassName}(id: number) {
return defHttp.get({ url: '${baseURL}/get?id=' + id })
return defHttp.get({ url: `${baseURL}/get?id=${id}` })
}
// 新增${table.classComment}
export function create${simpleClassName}(data) {
return defHttp.post({ url: '${baseURL}/create', data })
return defHttp.post({ url: '${baseURL}/create', data })
}
// 修改${table.classComment}
export function update${simpleClassName}(data) {
return defHttp.put({ url: '${baseURL}/update', data })
return defHttp.put({ url: '${baseURL}/update', data })
}
// 删除${table.classComment}
export function delete${simpleClassName}(id: number) {
return defHttp.delete({ url: '${baseURL}/delete?id=' + id })
return defHttp.delete({ url: `${baseURL}/delete?id=${id}` })
}
// 导出${table.classComment} Excel

View File

@@ -1,4 +1,5 @@
import { BasicColumn, FormSchema, useRender } from '@/components/Table'
import type { BasicColumn, FormSchema } from '@/components/Table'
import { useRender } from '@/components/Table'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
export const columns: BasicColumn[] = [
@@ -92,13 +93,13 @@ export const createFormSchema: FormSchema[] = [
#elseif($column.htmlType == "imageUpload")## 图片上传
component: 'FileUpload',
componentProps: {
fileType: 'file',
fileType: 'image',
maxCount: 1,
},
#elseif($column.htmlType == "fileUpload")## 文件上传
component: 'FileUpload',
componentProps: {
fileType: 'image',
fileType: 'file',
maxCount: 1,
},
#elseif($column.htmlType == "editor")## 文本编辑器
@@ -132,6 +133,11 @@ export const createFormSchema: FormSchema[] = [
},
#elseif($column.htmlType == "datetime")## 时间框
component: 'DatePicker',
componentProps: {
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
},
#elseif($column.htmlType == "textarea")## 文本域
component: 'InputTextArea',
#end
@@ -154,7 +160,7 @@ export const updateFormSchema: FormSchema[] = [
#set ($javaField = $column.javaField)
#set ($AttrName = $column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
#set ($comment = $column.columnComment)
#if (!$column.primaryKey)## 忽略主键,不用在表单里
#if (!$column.primaryKey)## 忽略主键,不用在表单里
{
label: '${comment}',
field: '${javaField}',
@@ -164,45 +170,57 @@ export const updateFormSchema: FormSchema[] = [
#if ($column.htmlType == "input")
component: 'Input',
#elseif($column.htmlType == "imageUpload")## 图片上传
component: 'Upload',
component: 'FileUpload',
componentProps: {
fileType: 'image',
maxCount: 1,
},
#elseif($column.htmlType == "fileUpload")## 文件上传
component: 'Upload',
#elseif($column.htmlType == "editor")## 文本编辑器
component: 'Editor',
component: 'FileUpload',
componentProps: {
fileType: 'file',
maxCount: 1,
},
#elseif($column.htmlType == "editor")## 文本编辑器component: 'Editor',
#elseif($column.htmlType == "select")## 下拉框
component: 'Select',
componentProps: {
#if ("" != $dictType)## 有数据字典
options: getDictOptions(DICT_TYPE.$dictType.toUpperCase(), 'number'),
options: getDictOptions(DICT_TYPE.$dictType.toUpperCase(), 'number'),
#else##没数据字典
options:[],
options:[],
#end
},
#elseif($column.htmlType == "checkbox")## 多选框
component: 'Checkbox',
componentProps: {
#if ("" != $dictType)## 有数据字典
options: getDictOptions(DICT_TYPE.$dictType.toUpperCase(), 'number'),
options: getDictOptions(DICT_TYPE.$dictType.toUpperCase(), 'number'),
#else##没数据字典
options:[],
options:[],
#end
},
#elseif($column.htmlType == "radio")## 单选框
component: 'RadioButtonGroup',
componentProps: {
#if ("" != $dictType)## 有数据字典
options: getDictOptions(DICT_TYPE.$dictType.toUpperCase(), 'number'),
options: getDictOptions(DICT_TYPE.$dictType.toUpperCase(), 'number'),
#else##没数据字典
options:[],
options:[],
#end
},
#elseif($column.htmlType == "datetime")## 时间框
component: 'DatePicker',
componentProps: {
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
valueFormat: 'x',
},
#elseif($column.htmlType == "textarea")## 文本域
component: 'InputTextArea',
#end
},
#end
#end
#end
#end
]

View File

@@ -9,9 +9,10 @@ import { create${simpleClassName}, get${simpleClassName}, update${simpleClassNam
defineOptions({ name: '${table.className}Modal' })
const emit = defineEmits(['success', 'register'])
const { t } = useI18n()
const { createMessage } = useMessage()
const emit = defineEmits(['success', 'register'])
const isUpdate = ref(true)
const [registerForm, { setFieldsValue, resetFields, resetSchema, validate }] = useForm({
@@ -37,11 +38,11 @@ async function handleSubmit() {
try {
const values = await validate()
setModalProps({ confirmLoading: true })
if (unref(isUpdate)) {
if (unref(isUpdate))
await update${simpleClassName}(values)
} else {
else
await create${simpleClassName}(values)
}
closeModal()
emit('success')
createMessage.success(t('common.saveSuccessText'))
@@ -51,7 +52,7 @@ async function handleSubmit() {
}
</script>
<template>
<BasicModal v-bind="$attrs" @register="registerModal" :title="isUpdate ? t('action.edit') : t('action.create')" @ok="handleSubmit">
<BasicModal v-bind="$attrs" :title="isUpdate ? t('action.edit') : t('action.create')" @register="registerModal" @ok="handleSubmit">
<BasicForm @register="registerForm" />
</BasicModal>
</template>

View File

@@ -1,12 +1,12 @@
<script lang="ts" setup>
import ${simpleClassName}Modal from './${simpleClassName}Modal.vue'
import ${ simpleClassName }Modal from './${simpleClassName}Modal.vue'
import { columns, searchFormSchema } from './${classNameVar}.data'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { useModal } from '@/components/Modal'
import { IconEnum } from '@/enums/appEnum'
import { BasicTable, useTable, TableAction } from '@/components/Table'
import { delete${simpleClassName}, export${simpleClassName}, get${simpleClassName}Page } from '@/api/${table.moduleName}/${classNameVar}'
import { delete${ simpleClassName }, export${ simpleClassName }, get${ simpleClassName } Page } from '@/api/${table.moduleName}/${classNameVar}'
defineOptions({ name: '${table.className}' })
@@ -16,17 +16,17 @@ const [registerModal, { openModal }] = useModal()
const [registerTable, { getForm, reload }] = useTable({
title: '${table.classComment}列表',
api: get${simpleClassName}Page,
columns,
formConfig: { labelWidth: 120, schemas: searchFormSchema },
useSearchForm: true,
showTableSetting: true,
actionColumn: {
width: 140,
title: t('common.action'),
dataIndex: 'action',
fixed: 'right',
},
api: get${ simpleClassName }Page,
columns,
formConfig: { labelWidth: 120, schemas: searchFormSchema },
useSearchForm: true,
showTableSetting: true,
actionColumn: {
width: 140,
title: t('common.action'),
dataIndex: 'action',
fixed: 'right',
},
})
function handleCreate() {
@@ -43,14 +43,14 @@ async function handleExport() {
iconType: 'warning',
content: t('common.exportMessage'),
async onOk() {
await export${simpleClassName}(getForm().getFieldsValue())
await export${ simpleClassName } (getForm().getFieldsValue())
createMessage.success(t('common.exportSuccessText'))
},
})
}
async function handleDelete(record: Recordable) {
await delete${simpleClassName}(record.id)
await delete${ simpleClassName } (record.id)
createMessage.success(t('common.delSuccessText'))
reload()
}
@@ -89,4 +89,4 @@ async function handleDelete(record: Recordable) {
</BasicTable>
<${simpleClassName}Modal @register="registerModal" @success="reload()" />
</div>
</template>
</template>

View File

@@ -59,31 +59,6 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest {
@MockBean
private FileClientFactory fileClientFactory;
@Test
public void testInitLocalCache() {
// mock 数据
FileConfigDO configDO1 = randomFileConfigDO().setId(1L).setMaster(true);
fileConfigMapper.insert(configDO1);
FileConfigDO configDO2 = randomFileConfigDO().setId(2L).setMaster(false);
fileConfigMapper.insert(configDO2);
// mock fileClientFactory 获得 master
FileClient masterFileClient = mock(FileClient.class);
when(fileClientFactory.getFileClient(eq(1L))).thenReturn(masterFileClient);
// 调用
fileConfigService.initLocalCache();
// 断言 fileClientFactory 调用
verify(fileClientFactory).createOrUpdateFileClient(eq(1L),
eq(configDO1.getStorage()), eq(configDO1.getConfig()));
verify(fileClientFactory).createOrUpdateFileClient(eq(2L),
eq(configDO2.getStorage()), eq(configDO2.getConfig()));
assertSame(masterFileClient, fileConfigService.getMasterFileClient());
// 断言 fileConfigCache 缓存
assertEquals(2, fileConfigService.getFileConfigCache().size());
assertEquals(configDO1, fileConfigService.getFileConfigCache().get(0));
assertEquals(configDO2, fileConfigService.getFileConfigCache().get(1));
}
@Test
public void testCreateFileConfig_success() {
// 准备参数
@@ -102,6 +77,8 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest {
assertFalse(fileConfig.getMaster());
assertEquals("/yunai", ((LocalFileClientConfig) fileConfig.getConfig()).getBasePath());
assertEquals("https://www.iocoder.cn", ((LocalFileClientConfig) fileConfig.getConfig()).getDomain());
// 验证 cache
assertNull(fileConfigService.getClientCache().getIfPresent(fileConfigId));
}
@Test
@@ -125,6 +102,8 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest {
assertPojoEquals(reqVO, fileConfig, "config");
assertEquals("/yunai2", ((LocalFileClientConfig) fileConfig.getConfig()).getBasePath());
assertEquals("https://doc.iocoder.cn", ((LocalFileClientConfig) fileConfig.getConfig()).getDomain());
// 验证 cache
assertNull(fileConfigService.getClientCache().getIfPresent(fileConfig.getId()));
}
@Test
@@ -149,6 +128,8 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest {
// 断言数据
assertTrue(fileConfigMapper.selectById(dbFileConfig.getId()).getMaster());
assertFalse(fileConfigMapper.selectById(masterFileConfig.getId()).getMaster());
// 验证 cache
assertNull(fileConfigService.getClientCache().getIfPresent(0L));
}
@Test
@@ -169,6 +150,8 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest {
fileConfigService.deleteFileConfig(id);
// 校验数据不存在了
assertNull(fileConfigMapper.selectById(id));
// 验证 cache
assertNull(fileConfigService.getClientCache().getIfPresent(id));
}
@Test
@@ -250,14 +233,38 @@ public class FileConfigServiceImplTest extends BaseDbUnitTest {
@Test
public void testGetFileClient() {
// mock 数据
FileConfigDO fileConfig = randomFileConfigDO().setMaster(false);
fileConfigMapper.insert(fileConfig);
// 准备参数
Long id = randomLongId();
Long id = fileConfig.getId();
// mock 获得 Client
FileClient fileClient = new LocalFileClient(id, new LocalFileClientConfig());
when(fileClientFactory.getFileClient(eq(id))).thenReturn(fileClient);
// 调用,并断言
assertSame(fileClient, fileConfigService.getFileClient(id));
// 断言缓存
verify(fileClientFactory).createOrUpdateFileClient(eq(id), eq(fileConfig.getStorage()),
eq(fileConfig.getConfig()));
}
@Test
public void testGetMasterFileClient() {
// mock 数据
FileConfigDO fileConfig = randomFileConfigDO().setMaster(true);
fileConfigMapper.insert(fileConfig);
// 准备参数
Long id = fileConfig.getId();
// mock 获得 Client
FileClient fileClient = new LocalFileClient(id, new LocalFileClientConfig());
when(fileClientFactory.getFileClient(eq(0L))).thenReturn(fileClient);
// 调用,并断言
assertSame(fileClient, fileConfigService.getMasterFileClient());
// 断言缓存
verify(fileClientFactory).createOrUpdateFileClient(eq(0L), eq(fileConfig.getStorage()),
eq(fileConfig.getConfig()));
}
private FileConfigDO randomFileConfigDO() {

View File

@@ -139,4 +139,5 @@ public class FileServiceImplTest extends BaseDbUnitTest {
// 断言
assertSame(result, content);
}
}