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

[数据模型] 新增缓存配置。

上级 de7de381
//package com.tykj.workflowcore.model_layer.config;
//
//
//import com.github.benmanes.caffeine.cache.CacheLoader;
//import com.github.benmanes.caffeine.cache.Caffeine;
//import org.springframework.cache.CacheManager;
//import org.springframework.cache.annotation.EnableCaching;
//import org.springframework.cache.caffeine.CaffeineCacheManager;
//import org.springframework.cache.concurrent.ConcurrentMapCache;
//import org.springframework.cache.support.SimpleCacheManager;
//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;
//
//
///**
// * @Author WWW
// * @Description
// * @Date 10:47 2021/3/26
// * @return
// **/
//@Configuration
//@EnableCaching
//public class MyCacheConfig {
//
// @Bean
// public CacheManager cacheManager() {
// /*
// api + cache spring cache + hashmap
// myCode + redis
// spring cache + caffeine
// */
package com.tykj.workflowcore.model_layer.config;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.persistence.EntityManagerFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
/**
* @Author WWW
* @Description
* @Date 10:47 2021/3/26
* @return
**/
@Configuration
@EnableCaching
public class MyCacheConfig {
@Autowired
EntityManagerFactory entityManagerFactory;
@Bean
public CacheManager cacheManager() {
/*
api + cache spring cache + hashmap
myCode + redis
spring cache + caffeine
*/
// SimpleCacheManager cacheManager = new SimpleCacheManager();
//
//// CaffeineCacheManager cacheManager = new CaffeineCacheManager();
//// Caffeine caffeine = Caffeine.newBuilder()
//// /* cache的初始容量值 */
//// .initialCapacity(150)
//// //maximumSize用来控制cache的最大缓存数量,maximumSize和maximumWeight(最大权重)不可以同时使用,
//// .maximumSize(1000);
//// //最后一次写入或者访问后过久过期
////// .expireAfterAccess(10, TimeUnit.SECONDS)
////// //创建或更新之后多久刷新,需要设置cacheLoader
////// .refreshAfterWrite(5, TimeUnit.SECONDS);
//// cacheManager.setCaffeine(caffeine);
//// cacheManager.setCacheLoader(cacheLoader());
//// /* 根据名字可以创建多个cache,但是多个cache使用相同的策略 */
//// cacheManager.setCacheNames(Arrays
//// .asList("tableInfos"));
//// //是否允许值为空
//// cacheManager.setAllowNullValues(false);
// cacheManager.setCaches(Collections.singletonList(new ConcurrentMapCache("tableInfos")));
// return cacheManager;
// }
//
//
// @Bean
// public CacheLoader<Object, Object> cacheLoader() {
// return new CacheLoader<Object, Object>() {
// @Override
// public Object load(Object key) {
// return null;
// }
// // 重写这个方法将oldValue值返回回去,进而刷新缓存
// @Override
// public Object reload(Object key, Object oldValue) {
// return oldValue;
// }
// };
// }
//}
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
Caffeine caffeine = Caffeine.newBuilder()
/* cache的初始容量值 */
.initialCapacity(150)
//maximumSize用来控制cache的最大缓存数量,maximumSize和maximumWeight(最大权重)不可以同时使用,
.maximumSize(1000)
//最后一次写入或者访问后过久过期
.expireAfterAccess(30, TimeUnit.DAYS)
// //创建或更新之后多久刷新,需要设置cacheLoader
.refreshAfterWrite(5, TimeUnit.SECONDS);
cacheManager.setCaffeine(caffeine);
cacheManager.setCacheLoader(cacheLoader());
/* 根据名字可以创建多个cache,但是多个cache使用相同的策略 */
cacheManager.setCacheNames(Arrays.asList("tableInfos"));
//是否允许值为空
cacheManager.setAllowNullValues(false);
/* cacheManager.setCaches(Collections.singletonList(new ConcurrentMapCache("tableInfos"))); */
return cacheManager;
}
@Bean
public CacheLoader cacheLoader(){
return new CacheLoader() {
@Nullable
@Override
public Object load(@NonNull Object o) {
return null;
}
@Nullable
@Override
public Object reload(@NonNull Object key, @NonNull Object oldValue) {
return oldValue;
}
};
}
@Bean
public MetadataSources metadataSources(){
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
StandardServiceRegistry serviceRegistry = sessionFactory.getSessionFactoryOptions().getServiceRegistry();
return new MetadataSources(serviceRegistry);
}
}
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
......@@ -17,7 +16,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -28,6 +27,7 @@ import java.util.Map;
* @Date 2021/2/26 13:35
* @Version 1.0
*/
@Slf4j
@RestController
@RequestMapping("/model")
@Api(tags = "数据模型层接口")
......@@ -50,7 +50,7 @@ public class ModelController {
try {
tableInfos = modelService.listAllEntities(searchTableInfoVo);
} catch (SQLException throwables) {
return ResultUtil.failed("因为某些神秘原因,数据查询失败!");
return ResultUtil.failed("数据查询失败!");
}
return ResultUtil.success(tableInfos, "数据查询成功!");
......@@ -85,7 +85,12 @@ public class ModelController {
return ResultUtil.failed("表已经存在!");
}
}
long start = System.currentTimeMillis();
modelService.newTable(tableVO);
long end = System.currentTimeMillis();
log.warn("创建总用时为:{}秒",(end-start)/1000.0);
return ResultUtil.success("", "新建成功!");
}
......@@ -105,7 +110,7 @@ public class ModelController {
if (i==0){
return ResultUtil.success("", "数据插入成功!");
}
return ResultUtil.success("","模型类型不支持插入数据!");
return ResultUtil.failed("模型类型不支持插入数据!");
}
......@@ -146,8 +151,11 @@ public class ModelController {
@ApiOperation("编辑操作")
@PutMapping("/update")
public ResponseEntity updateTable(@RequestBody UpdateTableInfoVO updateTableInfoVO){
long start = System.currentTimeMillis();
int i = modelService.updateTable(updateTableInfoVO);
if (i==1){
long end = System.currentTimeMillis();
log.warn("创建总用时为:{}秒",(end-start)/1000.0);
return ResultUtil.success("","修改成功!");
}
return ResultUtil.success("业务类型不支持修改!");
......
......@@ -4,6 +4,7 @@ package com.tykj.workflowcore.model_layer.service;
import com.tykj.workflowcore.model_layer.entity.ColumnInfo;
import com.tykj.workflowcore.model_layer.entity.TableInfo;
import com.tykj.workflowcore.model_layer.entity.vo.*;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
......@@ -31,7 +32,7 @@ public interface ModelService {
* @return
* @throws SQLException
*/
// @Cacheable(cacheNames = "tableInfos")
@Cacheable(cacheNames = "tableInfos",sync = true)
Page<TableInfo> listAllEntities(SearchTableInfoVo searchTableInfoVo) throws SQLException;
......@@ -49,6 +50,7 @@ public interface ModelService {
* @param searchColumnInfoVo
* @return
*/
@Cacheable(cacheNames = "tableInfos")
List<ColumnInfo> showModelFields(SearchColumnInfoVo searchColumnInfoVo);
......@@ -58,8 +60,9 @@ public interface ModelService {
* @param tableVO
* @return
*/
// @CachePut(cacheNames = "tableInfos")
TableVO newTable(TableVO tableVO);
@CachePut(cacheNames = "tableInfos")
@CacheEvict(cacheNames = "tableInfos",allEntries = true)
TableInfo newTable(TableVO tableVO);
/**
* 根据表名插入数据
......@@ -94,10 +97,12 @@ public interface ModelService {
/**
* 修改表
* @param updateTableInfoVO
* @param updateTableInfoVO
* @return
*/
// @CachePut(cacheNames = "tableInfos")
@CachePut(cacheNames = "tableInfos")
@CacheEvict(cacheNames = "tableInfos",allEntries = true)
int updateTable(UpdateTableInfoVO updateTableInfoVO);
......@@ -106,8 +111,7 @@ public interface ModelService {
* @param delTableVO
* @return
*/
// @CacheEvict(cacheNames = "tableInfos")
// @Transactional
@CacheEvict(cacheNames = "tableInfos",allEntries = true)
int delTable(DelTableVO delTableVO);
......
......@@ -121,7 +121,7 @@ public class ModelImpl implements ModelService {
* @Date 16:16 2021/3/5
**/
@Override
public TableVO newTable(TableVO tableVO) {
public TableInfo newTable(TableVO tableVO) {
String xmlMapping = createTable(tableVO);
Integer modelType = tableVO.getModelType();
String parentTable = null;
......@@ -159,9 +159,10 @@ public class ModelImpl implements ModelService {
columnInfo.setDbId(tableInfo.getId());
columnInfoDao.save(columnInfo);
}
//关闭会话
session.close();
return tableVO;
return tableInfo;
}
/**
......@@ -219,8 +220,8 @@ public class ModelImpl implements ModelService {
* @Date 16:17 2021/3/5
**/
public void insertValue(String tableName, String xml, Map map) {
CreateTableUtil creatTableUtil = new CreateTableUtil();
Session newSession = creatTableUtil.getSession(entityManagerFactory, xml);
CreateTableUtil createTableUtil = new CreateTableUtil();
Session newSession = createTableUtil.getSession(entityManagerFactory, xml);
SessionImpl session = (SessionImpl) newSession;
EntityPersister entityPersister = session.getEntityPersister(tableName, map);
Type[] propertyTypes = entityPersister.getPropertyTypes();
......
......@@ -7,6 +7,14 @@ import com.tykj.workflowcore.model_layer.entity.vo.TableAndColumnInfoVO;
import com.tykj.workflowcore.model_layer.myEnum.ModelType;
import com.tykj.workflowcore.model_layer.service.ModelService;
import org.aspectj.lang.annotation.Before;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.query.Query;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.schema.TargetType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
......@@ -19,7 +27,10 @@ import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.persistence.EntityManagerFactory;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
......@@ -49,6 +60,12 @@ class WorkflowCoreApplicationTests {
@Autowired
ModelService modelService;
@Autowired
MetadataSources metadataSources;
@Autowired
EntityManagerFactory entityManagerFactory;
@Before("")
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(modelController).build();
......@@ -193,12 +210,8 @@ class WorkflowCoreApplicationTests {
*/
@Test
public void testDelTable() throws Exception {
String delete_JSON = "{\n" +
"\"id\":\"4\"\n" +
"}";
request = delete("/model/delete/")
.contentType(MediaType.APPLICATION_JSON)
.content(delete_JSON)
.param("id","5")
.accept(MediaType.APPLICATION_JSON_UTF8_VALUE);
mockMvc.perform(request)
.andExpect(status().isOk())
......@@ -208,12 +221,55 @@ class WorkflowCoreApplicationTests {
@Test
public void testAll() {
/*
Integer[] ids = {2, 3, 22};
// List<Integer> integers = Arrays.asList(ids);
//
// Object[] objects = integers.toArray();
List<Integer> integers = Arrays.asList(ids);
Object[] objects = integers.toArray();
TableAndColumnInfoVO all = modelService.getTableInfoAndColumnInfoByBatch(ids);
System.out.println(all);
*/
String xml=
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE hibernate-mapping PUBLIC\n" +
" \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n" +
" \"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">\n" +
"<hibernate-mapping>\n" +
" <class entity-name=\"teacher\" table=\"teacher\">\n" +
" <id name=\"id\" type=\"java.lang.Integer\" length=\"11\" unsaved-value=\"null\">\n" +
" <generator class=\"identity\" />\n" +
" </id> <property type=\"java.lang.Integer\" name=\"id\" length=\"11\" column=\"id\"/>\n" +
" <property type=\"java.lang.String\" name=\"name\" length=\"255\" column=\"name\"/>\n" +
" <property type=\"java.lang.Integer\" name=\"age\" length=\"11\" column=\"age\"/>\n" +
" <property type=\"java.lang.String\" name=\"sex\" length=\"255\" column=\"sex\"/>\n" +
"\n" +
" <set name=\"students\" table=\"stu_teacher_ref\" >\n" +
" \t<key column=\"id\"/>\n" +
" \t<many-to-many class=\"stu\" column=\"\"/>\n" +
" </set>\n" +
"\n" +
" </class>\n" +
"</hibernate-mapping>";
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
StandardServiceRegistry serviceRegistry = sessionFactory.getSessionFactoryOptions().getServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
sessionFactory.getSessionFactoryOptions();
metadataSources.addInputStream(new ByteArrayInputStream(xml.getBytes()));
Metadata metadata = metadataSources.buildMetadata();
//更新数据库Schema,如果不存在就创建表,存在就更新字段,不会影响已有数据
SchemaUpdate schemaUpdate = new SchemaUpdate();
schemaUpdate.execute(EnumSet.of(TargetType.DATABASE), metadata, serviceRegistry);
metadata = metadataSources.buildMetadata();
//创建会话工厂
SessionFactory newSessionFactory = metadata.buildSessionFactory();
//保存对象
Session newSession = newSessionFactory.openSession();
Query query = newSession.createQuery("");
List list = query.list();
list.forEach(o -> System.out.println(o));
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论