update 新增mongo代码生成器,修复IdUtils的全局ID生成

master
管理员 1 year ago
parent 9a0968f87c
commit d1e46afb79

@ -26,6 +26,10 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
</dependency>
<!-- Mysql驱动包 --> <!-- Mysql驱动包 -->
<dependency> <dependency>

@ -0,0 +1,298 @@
package com.ruoyi;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Info;
import lombok.Data;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.junit.jupiter.api.Test;
import org.springframework.data.annotation.Id;
import java.io.File;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Info
public class MongoGenerator {
/**
* mongo
*/
private String packageName = "com.ruoyi.jobs";
/**
*
*/
private String moduleName = "jobs";
@Test
public void generate() throws Exception {
List<BaseInfo> entityList = scan(); //所有编写了@Info的实体类
// List<BaseInfo> entityList = scan("JobsTag1");//编写了@Info的实体类中的某些类
System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entityList));
generate(entityList);
System.out.println("完成");
}
public void generate(List<BaseInfo> entityList) throws Exception {
File[] fs = getOutPath();
/**
*
*/
File root = fs[0];
/**
* java
*/
File javaRoot = fs[1];
for (BaseInfo entity : entityList) {
String code = generate("query.vm", entity, entityList);
new File(javaRoot, "mongo/query").mkdirs();
FileUtil.writeString(code, new File(javaRoot, "mongo/query/" + entity.toUpperName() + "Query.java"), "UTF-8");
code = generate("api.vm", entity, entityList);
new File(javaRoot, "api").mkdirs();
FileUtil.writeString(code, new File(javaRoot, "api/" + entity.toUpperName() + "Api.java"), "UTF-8");
code = generate("api.js.vm", entity, entityList);
new File(root, "admin-ui/src/views/" + moduleName + "/api").mkdirs();
FileUtil.writeString(code, new File(root, "admin-ui/src/views/" + moduleName + "/api/" + entity.toSimpleLowerName() + ".js"), "UTF-8");
code = generate("index.vue.vm", entity, entityList);
new File(root, "admin-ui/src/views/" + moduleName + "/" + entity.toSimpleLowerName()).mkdirs();
FileUtil.writeString(code, new File(root, "admin-ui/src/views/" + moduleName + "/" + entity.toSimpleLowerName() + "/index.vue"), "UTF-8");
code = generate("WAdd.vue.vm", entity, entityList);
new File(root, "admin-ui/src/views/" + moduleName + "/" + entity.toSimpleLowerName() + "/components").mkdirs();
FileUtil.writeString(code, new File(root, "admin-ui/src/views/" + moduleName + "/" + entity.toSimpleLowerName() + "/components/WAdd.vue"), "UTF-8");
code = generate("WEdit.vue.vm", entity, entityList);
FileUtil.writeString(code, new File(root, "admin-ui/src/views/" + moduleName + "/" + entity.toSimpleLowerName() + "/components/WEdit.vue"), "UTF-8");
}
String code = generate("sql.vm", null, entityList);
FileUtil.writeString(code, new File(root, moduleName + "-menu.sql"), "UTF-8");
}
/**
* 使
* @param template
* @param entity
* @param list
* @return
* @throws Exception
*/
public String generate(String template, BaseInfo entity, List<BaseInfo> list) throws Exception {
VelocityEngine ve = new VelocityEngine();
ve.init();
VelocityContext context = new VelocityContext();
context.put("package", packageName);
context.put("entity", entity);
context.put("list", list);
context.put("moduleName", moduleName);
StringWriter writer = new StringWriter();
template = ResourceUtil.readUtf8Str("classpath:/generator/" + template);
ve.evaluate(context, writer, this.getClass().getName(), template);
return writer.toString();
}
/**
* java
*
* @return
*/
public File[] getOutPath() {
Set<String> paths = ClassUtil.getClassPaths(packageName);
if (CollUtil.isEmpty(paths) || paths.size() != 1) {
throw new RuntimeException("不能确定java包源目录");
}
String path = paths.iterator().next();
File file = new File(path.replace("/target/classes/", "/src/main/java/"));
File root = new File(path.substring(0, path.indexOf("/target/classes/"))).getParentFile();
return new File[]{root, file};
}
/**
*
*
* @param includes
* @return
*/
public List<BaseInfo> scan(String... includes) {
Info defaultInfo = MongoGenerator.class.getAnnotation(Info.class);
List<BaseInfo> entityList = ListUtil.list(true);
ClassUtil.scanPackageByAnnotation(packageName + ".mongo", Info.class).stream().filter(c -> {
if (ArrayUtil.isEmpty(includes)) {
return true;
} else {
return ArrayUtil.indexOf(includes, c.getSimpleName()) > -1;
}
}).forEach(entityClazz -> {
BaseInfo entityInfo = loadByInfo(entityClazz.getAnnotation(Info.class));
entityList.add(entityInfo);
entityInfo.setClazz(entityClazz);
entityInfo.setJavaName(entityClazz.getSimpleName());
entityInfo.setModuleName(moduleName);
entityInfo.all = Arrays.stream(entityClazz.getDeclaredFields()).map(field -> {
BaseInfo info = null;
if (field.isAnnotationPresent(Info.class)) {
info = loadByInfo(field.getAnnotation(Info.class));
} else {
info = loadByInfo(defaultInfo);
}
info.setClazz(field.getType());
info.setJavaName(field.getName());
info.setIsId(field.isAnnotationPresent(Id.class));
info.setModuleName(moduleName);
return info;
}).sorted((a, b) -> a.order - b.order).collect(Collectors.toList());
entityInfo.cols = entityInfo.all.stream().filter(a -> !a.isId).collect(Collectors.toList());
entityInfo.id = entityInfo.all.stream().filter(a -> a.isId).findFirst().get();
});
return entityList;
}
public BaseInfo loadByInfo(Info info) {
BaseInfo base = new BaseInfo();
base.setAdd(info.add());
base.setUpdate(info.update());
base.setShow(info.show());
base.setOrder(info.order());
base.setName(info.value());
if (!info.addDefault().equals("")) {
base.setAddDefault(info.addDefault());
}
if (!info.updateDefault().equals("")) {
base.setUpdateDefault(info.updateDefault());
}
if (!info.comment().equals("")) {
base.setComment(info.comment());
}
return base;
}
@Data
public static class BaseInfo {
public Class<?> clazz;
public Field field;
/**
*
*/
public List<BaseInfo> all;
/**
*
*/
public List<BaseInfo> cols;
/**
*
*/
public BaseInfo id;
public Boolean isId = false;
public String name;
public String javaName;
public String moduleName;
public String toUpperName() {
return javaName.substring(0, 1).toUpperCase() + javaName.substring(1);
}
/**
*
*
* @return
*/
public String toSimpleUpperName() {
String n = toLowerName();
if (n.startsWith(moduleName)) {
return n.substring(moduleName.length());
} else {
return toUpperName();
}
}
public String toSimpleLowerName() {
String n = toLowerName();
if (n.startsWith(moduleName)) {
n = n.substring(moduleName.length());
return n.substring(0, 1).toLowerCase() + n.substring(1);
} else {
return toLowerName();
}
}
public String toLowerName() {
return javaName.substring(0, 1).toLowerCase() + javaName.substring(1);
}
public String comment;
/**
* @param tabNum
* @return
*/
public String toComment(int tabNum) {
if (tabNum < 0) {
tabNum = 0;
}
String tabs = tabNum > 0 ? String.format("%" + (tabNum * 2) + "s", "") + " * " : " * ";
if (StrUtil.isNotBlank(comment)) {
return tabs + comment.replace("\n", "\n" + tabs);
} else {
return tabs;
}
}
public boolean show;
public boolean add;
public String addDefault;
public boolean update;
public String updateDefault;
public int order;
}
}

@ -0,0 +1,55 @@
#set($a="#")
<template>
<el-dialog title="添加${entity.name}" v-model="show" width="400px" destroy-on-close append-to-body draggable>
<el-form label-width="120px">
#foreach($item in $entity.cols)
#if($item.add && !$item.addDefault)
<el-form-item label="${item.name}" prop="${item.toLowerName()}">
<el-input v-model="form.${item.toLowerName()}" placeholder="${item.name}" />
</el-form-item>
#end
#end
</el-form>
<template ${a}footer>
<div class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="show = false">取 消</el-button>
</div>
</template>
</el-dialog>
</template>
<script setup>
import { ref, getCurrentInstance } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import * as api from '../../api/${entity.toSimpleLowerName()}'
const emit = defineEmits(["success"])
const { proxy } = getCurrentInstance()
const form = ref({});
const show = ref(false);
const open = async (obj = {}) => {
form.value = { ...obj };
show.value = true;
}
const submitForm = () => {
let loading = ElLoading.service({ fullscreen: true, lock: true, background: '${a}0001' })
api.doAdd(form.value).then(r=>{
ElMessage.success("添加成功")
show.value = false
emit("success", form.value)
}).finally(()=>{
loading.close()
})
}
defineExpose({ open });
</script>
<style lang="scss" scoped></style>

@ -0,0 +1,59 @@
#set($a="#")
<template>
<el-dialog title="修改${entity.name}" v-model="show" width="400px" destroy-on-close append-to-body draggable>
<el-form label-width="120px">
#foreach($item in $entity.all)
#if($item.update && !$item.updateDefault && !$item.isId)
<el-form-item label="${item.name}" prop="${item.toLowerName()}">
<el-input v-model="form.${item.toLowerName()}" placeholder="${item.name}" />
</el-form-item>
#else
<el-form-item label="${item.name}" prop="${item.toLowerName()}">
{{ form.${item.toLowerName()} }}
</el-form-item>
#end
#end
</el-form>
<template ${a}footer>
<div class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="show = false">取 消</el-button>
</div>
</template>
</el-dialog>
</template>
<script setup>
import { ref, getCurrentInstance } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import * as api from '../../api/${entity.toSimpleLowerName()}'
const emit = defineEmits(["success"])
const { proxy } = getCurrentInstance()
const form = ref({});
const show = ref(false);
const open = async (obj = {}) => {
form.value = { ...obj };
show.value = true;
}
const submitForm = () => {
let loading = ElLoading.service({ fullscreen: true, lock: true, background: '${a}0001' })
api.doUpdate(form.value).then(r=>{
ElMessage.success("修改成功")
show.value = false
emit("success", form.value)
}).finally(()=>{
loading.close()
})
}
defineExpose({ open });
</script>
<style lang="scss" scoped></style>

@ -0,0 +1,13 @@
import request from '@/utils/request'
const base = '/${moduleName}/${entity.toSimpleLowerName()}/'
export const doAdd = (data) => request.post(base, data)
export const doUpdate = (data) => request.put(base, data)
export const doDelete = (ids) => request.delete(base+ids)
export const doPage = (params) => request.get(base + 'page', { params })
export const doGet = (id) => request.get(base + id)

@ -0,0 +1,99 @@
package ${package}.api;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.Page;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.JsonUtils;
import ${package}.mongo.${entity.toUpperName()};
import ${package}.mongo.query.${entity.toUpperName()}Query;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import static com.ruoyi.common.utils.MongoUtil.*;
/**
* ${entity.name}
${entity.toComment(0)}
*/
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/${moduleName}/${entity.toSimpleLowerName()}/")
public class ${entity.toUpperName()}Api {
@GetMapping("/{id}")
@SaCheckPermission("${moduleName}:${entity.toSimpleLowerName()}:query")
public ${entity.toUpperName()} id(@NotNull(message = "编号不能为空") @PathVariable Long id) {
return findById(${entity.toUpperName()}.class, id);
}
@SaCheckPermission("${moduleName}:${entity.toSimpleLowerName()}:page")
@GetMapping("/page")
public Page<${entity.toUpperName()}> page(Page<${entity.toUpperName()}> page, ${entity.toUpperName()} ${entity.toLowerName()}, ${entity.toUpperName()}Query query) {
return findPage(${entity.toUpperName()}.class, page, criteria(${entity.toLowerName()}), query.where());
}
@SaCheckPermission("${moduleName}:${entity.toSimpleLowerName()}:add")
@Log(title = "${entity.name}", businessType = BusinessType.INSERT)
@RepeatSubmit
@PostMapping
public void add(@Validated(AddGroup.class) @RequestBody ${entity.toUpperName()} ${entity.toLowerName()}) {
if (log.isTraceEnabled()) {
log.trace("${entity.name}添加参数:{}", JsonUtils.toJsonString(${entity.toLowerName()}));
}
fillId(${entity.toLowerName()});
#foreach($item in $entity.cols)
#if($item.add)
#if($item.addDefault)
${entity.toLowerName()}.set${item.toUpperName()}(${item.addDefault});
#end
#else
${entity.toLowerName()}.set${item.toUpperName()}(null);
#end
#end
doInsert(${entity.toLowerName()});
}
@SaCheckPermission("${moduleName}:${entity.toSimpleLowerName()}:update")
@Log(title = "${entity.name}", businessType = BusinessType.UPDATE)
@RepeatSubmit
@PutMapping
public void update(@Validated(EditGroup.class) @RequestBody ${entity.toUpperName()} ${entity.toLowerName()}) {
if (log.isTraceEnabled()) {
log.trace("${entity.name}修改参数:{}", JsonUtils.toJsonString(${entity.toLowerName()}));
}
#foreach($item in $entity.cols)
#if($item.update)
#if($item.updateDefault)
${entity.toLowerName()}.set${item.toUpperName()}(${item.updateDefault});
#end
#else
${entity.toLowerName()}.set${item.toUpperName()}(null);
#end
#end
doUpdate(${entity.toLowerName()});
}
@SaCheckPermission("${moduleName}:${entity.toSimpleLowerName()}:delete")
@Log(title = "${entity.name}", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public void remove(@NotEmpty(message = "编号不能为空") @PathVariable Long[] ids) {
doRemove(${entity.toUpperName()}.class, conditions().put("_id$in", ids).query());
}
}

@ -0,0 +1,132 @@
#set($a="$")
#set($b="#")
<template>
<div class="${entity.toSimpleLowerName()}-root">
<div class="search-form">
<el-input v-model="search.key" placeholder="模糊搜索关键字" clearable style="width: 20em;" />
<div style="width: 20em;"><el-date-picker v-model="daterange" value-format="YYYY-MM-DD" type="daterange"
range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" /></div>
<el-button type="default" @click="handleSearch">搜索</el-button>
<div style="flex-grow: 2;"></div>
<el-button v-hasPermi="['${moduleName}:${entity.toSimpleLowerName()}:add']" type="primary" @click="proxy.${a}refs.addRef.open();">新增</el-button>
</div>
<el-table :data="list" border stripe height="100%" v-loading="loading">
#foreach($item in $entity.all)
<el-table-column #if(!$item.show)v-if="false" #end label="${item.name}" align="center" prop="${item.toLowerName()}" />
#end
<el-table-column label="操作" fixed="right" width="100" align="center">
<template ${b}default="{ row }">
<el-button-group>
<el-button v-hasPermi="['${moduleName}:${entity.toSimpleLowerName()}:update']" type="primary" link
@click="proxy.${a}refs.editRef.open(row);">修改</el-button>
<el-button v-hasPermi="['${moduleName}:${entity.toSimpleLowerName()}:delete']" type="danger" link @click="handleDelete(row)">删除</el-button>
</el-button-group>
</template>
</el-table-column>
</el-table>
<pagination v-show="total > 0" :page-sizes="[10, 20, 50]" :total="total" v-model:page="query.current"
v-model:limit="query.size" @pagination="loadPage" />
<WAdd ref="addRef" @success="loadPage()" />
<WEdit ref="editRef" @success="loadPage()" />
</div>
</template>
<script setup>
import { ref, getCurrentInstance, watch, onMounted, computed, onUnmounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import * as api from '../api/${entity.toSimpleLowerName()}'
import WAdd from './components/WAdd.vue'
import WEdit from './components/WEdit.vue'
const daterange = computed({
get() {
return search.value.beginDate ? [search.value.beginDate, search.value.endDate] : []
},
set(value) {
if (value && value[0]) {
search.value.beginDate = value[0]
search.value.endDate = value[1]
} else {
search.value.beginDate = ""
search.value.endDate = ""
}
}
})
const { proxy } = getCurrentInstance()
// 搜索表单
const search = ref({})
// 查询参数
const query = ref({
current: 1,
size: 10,
orderBy: '${entity.id.toLowerName()} desc'
});
// 列表数据
const list = ref([]);
// 总数据量
const total = ref(0);
// 加载状态
const loading = ref(true);
// 加载分页数据
const loadPage = async () => {
loading.value = true
let r = await api.doPage(query.value)
list.value = r.data?.records || []
total.value = Number(r.data?.total || 0)
loading.value = false
}
// 执行搜索
const handleSearch = () => {
query.value = { ...query.value, ...search.value }
query.value.current = 1
loadPage()
}
handleSearch()
const handleDelete = async (row) => {
await ElMessageBox.confirm(`确定要删除这条记录吗?`)
await api.doDelete(row.${entity.id.toLowerName()})
ElMessage.success("删除成功")
loadPage()
}
</script>
<style lang="scss" scoped>
.${entity.toSimpleLowerName()}-root {
padding: 1rem;
.search-form {
display: flex;
flex-wrap: wrap;
align-items: center;
padding: 0 0 .3rem 0;
position: relative;
&>*:not(.el-select) {
margin: 0 .5rem .5rem 0;
display: flex;
align-items: center;
}
}
}
</style>

@ -0,0 +1,53 @@
package ${package}.mongo.query;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.mongodb.core.query.Criteria;
import static com.ruoyi.common.utils.MongoUtil.*;
/**
* ${entity.name}的查询条件
${entity.toComment(0)}
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ${entity.toUpperName()}Query {
// 设置请求日期参数格式
@org.springframework.format.annotation.DateTimeFormat(pattern = "yyyy-MM-dd")
// 设置使用@RequestBody时日期参数格式
// @com.fasterxml.jackson.annotation.JsonFormat(pattern = "yyyy-MM-dd")
private java.util.Date beginDate;
// @org.springframework.format.annotation.DateTimeFormat(pattern = "yyyy-MM-dd")
// private java.util.Date endDate;
//
// private String key;
public Criteria where() {
Criteria c = new Criteria();
// if (ObjUtil.isNotNull(beginDate) && ObjUtil.isNotNull(endDate)) {
// c = c.and("createTime").gte(beginDate).lte(DateUtil.endOfDay(endDate));
// }
// if(StrUtil.isNotBlank(key)){
// c=c.orOperator(
// conditions().put("name$like",key).criteria(),
// conditions().put("name1$like",key).criteria()
// );
// }
return c;
}
}

@ -0,0 +1,26 @@
set @id = (SELECT max(menu_id) from sys_menu)+1;
set @pid = '1';
set @icon = 'excel';
#set($a = "#")
#foreach($item in $list)
-- 菜单 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component,query_param, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values(@id, '${item.name}', @pid, '100', '${item.toSimpleLowerName()}', '${moduleName}/${item.toSimpleLowerName()}/index', '', 1, 0, 'C', '0', '0', '${moduleName}:${item.toSimpleLowerName()}:page', @icon, 'admin', sysdate(), '', null, '${item.name}');
-- 按钮 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values(@id+1, '查询', @id, '1', '${a}', '', 1, 0, 'F', '0', '0', '${moduleName}:${item.toSimpleLowerName()}:query', '${a}', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values(@id+2, '添加', @id, '2', '${a}', '', 1, 0, 'F', '0', '0', '${moduleName}:${item.toSimpleLowerName()}:add', '${a}', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values(@id+3, '修改', @id, '3', '${a}', '', 1, 0, 'F', '0', '0', '${moduleName}:${item.toSimpleLowerName()}:update', '${a}', 'admin', sysdate(), '', null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark)
values(@id+4, '删除', @id, '4', '${a}', '', 1, 0, 'F', '0', '0', '${moduleName}:${item.toSimpleLowerName()}:delete', '${a}', 'admin', sysdate(), '', null, '');
set @id = @id + 10;
#end

@ -0,0 +1,65 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.*;
/**
*
* mongodb
*/
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Info {
/**
*
*
* @return
*/
String value() default "";
/**
*
*
*
*
* @return
*/
String javaName() default "";
/**
*
* @return
*/
String comment() default "";
boolean show() default true;
/**
*
* @return
*/
boolean add() default true;
/**
*
* @return
*/
String addDefault() default "";
/**
*
* @return
*/
boolean update() default true;
/**
*
* @return
*/
String updateDefault() default "";
int order() default 0;
}

@ -26,6 +26,7 @@ public class IdUtils {
private static final String DEFAULT_GROUP_NAME = "default"; private static final String DEFAULT_GROUP_NAME = "default";
private static final String PREFIX = "id:"; private static final String PREFIX = "id:";
private static final String PREFIX_GLOBAL = "id:global:";
private static LocalDate day; private static LocalDate day;
@ -50,9 +51,9 @@ public class IdUtils {
* @return * @return
*/ */
public static Long nextId(String groupName) { public static Long nextId(String groupName) {
RedisAtomicLong counter = map.get(PREFIX + groupName); RedisAtomicLong counter = map.get(PREFIX_GLOBAL + groupName);
if (counter == null) { if (counter == null) {
counter = new RedisAtomicLong(PREFIX + groupName, redisTemplate.getConnectionFactory()); counter = new RedisAtomicLong(PREFIX_GLOBAL + groupName, redisTemplate.getConnectionFactory());
map.put(PREFIX + groupName, counter); map.put(PREFIX + groupName, counter);
} }
return counter.incrementAndGet(); return counter.incrementAndGet();
@ -73,7 +74,7 @@ public class IdUtils {
* @return * @return
*/ */
public static boolean nextIdInit(String groupName) { public static boolean nextIdInit(String groupName) {
return map.containsKey(PREFIX + groupName); return map.containsKey(PREFIX_GLOBAL + groupName);
} }
public static void nextIdInit(Long startId) { public static void nextIdInit(Long startId) {
@ -91,10 +92,10 @@ public class IdUtils {
* @param startId * @param startId
*/ */
public static void nextIdInit(String groupName, Long startId) { public static void nextIdInit(String groupName, Long startId) {
RedisAtomicLong counter = map.get(PREFIX + groupName); RedisAtomicLong counter = map.get(PREFIX_GLOBAL + groupName);
if (counter == null) { if (counter == null) {
counter = new RedisAtomicLong(PREFIX + groupName, redisTemplate.getConnectionFactory()); counter = new RedisAtomicLong(PREFIX_GLOBAL + groupName, redisTemplate.getConnectionFactory());
map.put(PREFIX + groupName, counter); map.put(PREFIX_GLOBAL + groupName, counter);
} }
counter.set(startId); counter.set(startId);
} }

Loading…
Cancel
Save