提交 c6fac988 authored 作者: ww1xhqc's avatar ww1xhqc

[数据模型] 修改了缓存配置,增加了类型长度错误拦截

上级 4bc4738e
......@@ -4,7 +4,10 @@ import com.tykj.workflowcore.base.entity.BaseEntity;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
import java.util.Date;
......@@ -31,4 +34,5 @@ public class EntityHandle {
}
}
}
......@@ -16,6 +16,8 @@ import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import static com.tykj.workflowcore.base.util.ClassUtil.loadClassByLoader;
/**
* @author HuangXiahao
* @version V1.0
......@@ -59,47 +61,48 @@ public class WorkflowCoreRunner implements CommandLineRunner {
}
}
//通过loader加载所有类
private List<Class<?>> loadClassByLoader(ClassLoader load) {
List<Class<?>> classes = new ArrayList<>();
try {
Enumeration<URL> urls = load.getResources("");
//放所有类型
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
//文件类型(其实是文件夹)
if (url.getProtocol().equals("file")) {
loadClassByPath(null, url.getPath(), classes, load);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
//通过文件路径加载所有类 root 主要用来替换path中前缀(除包路径以外的路径)
private void loadClassByPath(String root, String path, List<Class<?>> list, ClassLoader load) {
File f = new File(path);
if (root == null) root = f.getPath();
//判断是否是class文件
if (f.isFile() && f.getName().matches("^.*\\.class$")) {
try {
String classPath = f.getPath();
//截取出className 将路径分割符替换为.(windows是\ linux、mac是/)
String className = classPath.substring(root.length() + 1, classPath.length() - 6).replace('/', '.').replace('\\', '.');
list.add(load.loadClass(className));
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
File[] fs = f.listFiles();
if (fs == null) return;
for (File file : fs) {
loadClassByPath(root, file.getPath(), list, load);
}
}
}
// //通过loader加载所有类
// private List<Class<?>> loadClassByLoader(ClassLoader load) {
// List<Class<?>> classes = new ArrayList<>();
// try {
// Enumeration<URL> urls = load.getResources("");
// //放所有类型
// while (urls.hasMoreElements()) {
// URL url = urls.nextElement();
// //文件类型(其实是文件夹)
// if (url.getProtocol().equals("file")) {
// loadClassByPath(null, url.getPath(), classes, load);
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// return classes;
// }
//
// //通过文件路径加载所有类 root 主要用来替换path中前缀(除包路径以外的路径)
// private void loadClassByPath(String root, String path, List<Class<?>> list, ClassLoader load) {
// File f = new File(path);
// if (root == null) root = f.getPath();
// //判断是否是class文件
// if (f.isFile() && f.getName().matches("^.*\\.class$")) {
// try {
// String classPath = f.getPath();
// //截取出className 将路径分割符替换为.(windows是\ linux、mac是/)
// String className = classPath.substring(root.length() + 1, classPath.length() - 6).replace('/', '.').replace('\\', '.');
// list.add(load.loadClass(className));
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// } else {
// File[] fs = f.listFiles();
// if (fs == null) return;
// for (File file : fs) {
// loadClassByPath(root, file.getPath(), list, load);
// }
// }
// }
......
package com.tykj.workflowcore.base.result;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -11,6 +12,7 @@ import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
/**
......@@ -40,7 +42,16 @@ public class GlobalExceptionHandler {
}
/**
* 处理字段长度异常
* @param invalidFormatException
* @return
*/
@ExceptionHandler(InvalidFormatException.class)
public ResponseEntity handle(InvalidFormatException invalidFormatException){
log.warn(invalidFormatException.toString());
return ResultUtil.failed("字段长度错误,请修改为合适的长度!");
}
}
......@@ -12,6 +12,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
......@@ -28,26 +29,30 @@ public class MyCacheConfig {
@Bean
public CaffeineCacheManager cacheManager() {
//api + cache spring cache + hashmap
//mycode + redis
//spring cache + caffeine
// SimpleCacheManager cacheManager = new SimpleCacheManager();
/*
api + cache spring cache + hashmap
myCode + redis
spring cache + caffeine
SimpleCacheManager cacheManager = new SimpleCacheManager();
*/
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
Caffeine caffeine = Caffeine.newBuilder()
//cache的初始容量值
.initialCapacity(100)
/* cache的初始容量值 */
.initialCapacity(150)
//maximumSize用来控制cache的最大缓存数量,maximumSize和maximumWeight(最大权重)不可以同时使用,
.maximumSize(1000)
//最后一次写入或者访问后过久过期
.expireAfterAccess(500, TimeUnit.SECONDS)
.expireAfterAccess(10, TimeUnit.SECONDS)
//创建或更新之后多久刷新,需要设置cacheLoader
.refreshAfterWrite(10, TimeUnit.SECONDS);
.refreshAfterWrite(5, TimeUnit.SECONDS);
cacheManager.setCaffeine(caffeine);
cacheManager.setCacheLoader(cacheLoader());
// cacheManager.setCacheNames();//根据名字可以创建多个cache,但是多个cache使用相同的策略
cacheManager.setAllowNullValues(false);//是否允许值为空
// cacheManager.setCaches(Collections.singletonList(new ConcurrentMapCache("tableInfos")));
/* 根据名字可以创建多个cache,但是多个cache使用相同的策略 */
cacheManager.setCacheNames(Arrays
.asList("tableInfos"));
//是否允许值为空
cacheManager.setAllowNullValues(false);
/* cacheManager.setCaches(Collections.singletonList(new ConcurrentMapCache("tableInfos"))); */
return cacheManager;
}
......@@ -56,14 +61,12 @@ public class MyCacheConfig {
public CacheLoader<Object, Object> cacheLoader() {
return new CacheLoader<Object, Object>() {
@Override
public Object load(Object key) throws Exception {
public Object load(Object key) {
return null;
}
// 重写这个方法将oldValue值返回回去,进而刷新缓存
@Override
public Object reload(Object key, Object oldValue) throws Exception {
System.out.println("--refresh--:" + key);
public Object reload(Object key, Object oldValue) {
return oldValue;
}
};
......
package com.tykj.workflowcore.model_layer.controller;
import com.tykj.workflowcore.base.result.ApiException;
import com.tykj.workflowcore.base.result.ResultUtil;
import com.tykj.workflowcore.model_layer.entity.vo.*;
import com.tykj.workflowcore.model_layer.entity.TableInfo;
import com.tykj.workflowcore.model_layer.service.ModelService;
import com.tykj.workflowcore.model_layer.utils.ClassTypeLength;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -152,7 +154,7 @@ public class ModelController {
}
@ApiOperation("删除操作")
@DeleteMapping("/delete")
public ResponseEntity delTable( DelTableVO delTableVO) {
public ResponseEntity delTable(@RequestBody DelTableVO delTableVO) {
int i = modelService.delTable(delTableVO);
if (i==1){
......
......@@ -2,7 +2,7 @@ package com.tykj.workflowcore.model_layer.myEnum;
/**
* @ClassName ModelType
* @Description TODO
* @Description TODO 模型的3种类型
* @Author WWW
* @Date 2021/3/26 14:41
* @Version 1.0
......
......@@ -9,6 +9,8 @@ import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
......@@ -29,7 +31,7 @@ public interface ModelService {
* @return
* @throws SQLException
*/
@Cacheable(cacheNames = "tableInfos",key ="#searchTableInfoVo" )
@Cacheable(value = "tableInfos" )
Page<TableInfo> listAllEntities(SearchTableInfoVo searchTableInfoVo) throws SQLException;
......@@ -47,7 +49,6 @@ public interface ModelService {
* @param searchColumnInfoVo
* @return
*/
@Cacheable(cacheNames = "tableInfos",key ="#searchColumnInfoVo" )
List<ColumnInfo> showModelFields(SearchColumnInfoVo searchColumnInfoVo);
......@@ -57,6 +58,7 @@ public interface ModelService {
* @param tableVO
* @return
*/
@CachePut(value = "tableInfos")
TableVO newTable(TableVO tableVO);
/**
......@@ -95,7 +97,7 @@ public interface ModelService {
* @param updateTableInfoVO
* @return
*/
@CachePut(cacheNames = "tableInfos")
@CachePut(value = "tableInfos")
int updateTable(UpdateTableInfoVO updateTableInfoVO);
......@@ -104,7 +106,8 @@ public interface ModelService {
* @param delTableVO
* @return
*/
@CacheEvict(cacheNames = "tableInfos")
@CacheEvict(value = "tableInfos")
@Transactional
int delTable(DelTableVO delTableVO);
......
......@@ -2,6 +2,7 @@ package com.tykj.workflowcore.model_layer.service.impl;
import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;
import com.tykj.workflowcore.base.result.ApiException;
import com.tykj.workflowcore.model_layer.annotations.WorkFlowCoreNoScan;
import com.tykj.workflowcore.model_layer.dao.ColumnInfoDao;
import com.tykj.workflowcore.model_layer.dao.TableInfoDao;
......@@ -401,7 +402,7 @@ public class ModelImpl implements ModelService {
@Override
public List<TableInfo> listAllEntities() {
System.out.println("从数据库中取出的!");
return tableInfoDao.findAll();
}
......@@ -551,23 +552,21 @@ public class ModelImpl implements ModelService {
@Override
public int delTable(DelTableVO delTableVO) {
if (StringUtils.isNotEmpty(delTableVO.getDbName())) {
Optional<TableInfo> byId = tableInfoDao.findById(delTableVO.getId());
if (byId.isPresent()) {
TableInfo tableInfo = byId.get();
Integer modelType = tableInfo.getModelType();
if (modelType.equals(ModelType.BUSINESS) ) {
tableInfoDao.delete(tableInfo);
List<ColumnInfo> allByDbId = columnInfoDao.findAllByDbId(delTableVO.getId());
columnInfoDao.deleteInBatch(allByDbId);
jdbcTemplate.execute("drop table " + delTableVO.getDbName());
return 1;
}
if (!byId.isPresent()) {
throw new ApiException("此id已经被删除!");
} else {
TableInfo tableInfo = byId.get();
Integer modelType = tableInfo.getModelType();
if (modelType.equals(ModelType.BUSINESS) ) {
tableInfoDao.delete(tableInfo);
List<ColumnInfo> allByDbId = columnInfoDao.findAllByDbId(delTableVO.getId());
columnInfoDao.deleteInBatch(allByDbId);
jdbcTemplate.execute("drop table " + tableInfo.getModelName());
return 1;
}
}
return 0;
}
......
......@@ -11,9 +11,9 @@ import com.tykj.workflowcore.model_layer.entity.ColumnInfo;
* @Version 1.0
*/
public class ClassTypeLength {
private static String STRING="class java.lang.String";
private static String Integer="class java.lang.Integer";
private static String Double="class java.lang.Double";
public static String STRING="class java.lang.String";
public static String Integer="class java.lang.Integer";
public static String Double="class java.lang.Double";
public static void setLength(ColumnInfo columnInfo , String genericType){
......
package com.tykj.workflowcore.model_layer.utils;
import com.tykj.workflowcore.base.result.ApiException;
import com.tykj.workflowcore.model_layer.entity.vo.ColumnVO;
import com.tykj.workflowcore.model_layer.entity.vo.TableVO;
import org.hibernate.Session;
......@@ -10,6 +11,7 @@ import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.schema.TargetType;
import sun.rmi.runtime.NewThreadAction;
import javax.persistence.EntityManagerFactory;
import java.io.ByteArrayInputStream;
......@@ -24,7 +26,7 @@ import java.util.List;
* @Version 1.0
*/
public class CreateTableUtil {
public static String createTable(TableVO tableVO){
public static String createTable(TableVO tableVO) {
// 1sql-type="text" string 转为text文本,2长度超过会自动转换
List<ColumnVO> dataList = tableVO.getDataList();
String xmlMapping = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
......@@ -38,8 +40,9 @@ public class CreateTableUtil {
" <generator class=\"identity\" />\n" +
" </id>";
for (ColumnVO columnVO : dataList) {
xmlMapping +=
" <property type=\"" + columnVO.getFieldType() + "\" name=\"" + columnVO.getFieldName() +"\" length=\"" + columnVO.getFieldLength()+
" <property type=\"" + columnVO.getFieldType() + "\" name=\"" + columnVO.getFieldName() + "\" length=\"" + columnVO.getFieldLength()+
"\" column=\"" + columnVO.getFieldName() + "\"/>\n";
}
......@@ -51,7 +54,7 @@ public class CreateTableUtil {
}
public Session getSession(EntityManagerFactory entityManagerFactory,String xml){
public Session getSession(EntityManagerFactory entityManagerFactory, String xml) {
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
StandardServiceRegistry serviceRegistry = sessionFactory.getSessionFactoryOptions().getServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
......@@ -73,14 +76,13 @@ public class CreateTableUtil {
}
public static String getClassName(String aClass){
public static String getClassName(String aClass) {
int i = aClass.lastIndexOf(".");
String substring = aClass.substring(i+1);
String substring = aClass.substring(i + 1);
return substring;
}
public static String getTypeName(String aClass){
public static String getTypeName(String aClass) {
return aClass.replace("class ", "");
}
......
......@@ -19,6 +19,7 @@ import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
......@@ -123,8 +124,8 @@ class WorkflowCoreApplicationTests {
public void addModelTest() throws Exception {
String TableVo_json = "{\n" +
"\"modelName\":\"people2\",\n" +
"\"modelTitle\":\"人2\",\n" +
"\"modelName\":\"people\",\n" +
"\"modelTitle\":\"人\",\n" +
"\"modelType\":1,\n" +
"\"parentTable\":\"\",\n" +
"\"description\":\"详细信息\",\n" +
......@@ -142,7 +143,7 @@ class WorkflowCoreApplicationTests {
mockMvc.perform(request).andExpect(status().isOk())
.andExpect(content().string(not("")))
.andExpect(content().string(not("[]")))
.andExpect(content().string(equalTo("{\"message\":\"新建成功\",\"data\":\"\"}")))
.andExpect(content().string(equalTo("{\"message\":\"新建成功!\",\"data\":\"\"}")))
.andDo(print());//打印输出结果
}
......@@ -193,7 +194,7 @@ class WorkflowCoreApplicationTests {
@Test
public void testDelTable() throws Exception {
String delete_JSON = "{\n" +
"\"dbName\":\"testentity\"\n" +
"\"id\":\"4\"\n" +
"}";
request = delete("/model/delete/")
.contentType(MediaType.APPLICATION_JSON)
......@@ -208,9 +209,11 @@ class WorkflowCoreApplicationTests {
@Test
public void testAll() {
Integer[] ids = {2, 3, 22};
// List<Integer> integers = Arrays.asList(ids);
//
// Object[] objects = integers.toArray();
TableAndColumnInfoVO all = modelService.getTableInfoAndColumnInfoByBatch(ids);
System.out.println(all);
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论