spring启动时加载字典表数据放入缓存map

package com.anzhi.heifer.service.sys.impl;


import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


import javax.annotation.PostConstruct;


import net.sf.cglib.beans.BeanCopier;


import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.anzhi.heifer.bean.db1.sys.SysDic;
import com.anzhi.heifer.bean.db1.sys.SysDicType;
import com.anzhi.heifer.commons.constant.DictionaryConstants;
import com.anzhi.heifer.commons.utils.LogUtils;
import com.anzhi.heifer.dao.db1.sys.SysDicMapper;
import com.anzhi.heifer.dao.db1.sys.SysDicTypeMapper;
import com.anzhi.heifer.model.sys.SysDicModel;
import com.anzhi.heifer.model.sys.SysDicModel4Page;
import com.anzhi.heifer.service.sys.ISysDicService;


/**
 * 
 * <br>
 * <b>功能:</b>SysMenuService<br>
 * <b>作者:</b><br>
 * <b>日期:</b> Dec 9, 2011 <br>
 * <b>版权所有:<b><br>
 */
@Service("sysDicService")
public class SysDicServiceImpl implements ISysDicService<SysDicModel> {
private final static Logger log = LogManager.getLogger(SysDicServiceImpl.class);

/**
* 数据字典缓存map
*/
private static  ConcurrentHashMap<String, Map<String,String>> DICS = new ConcurrentHashMap<String,Map<String,String>>();

private static Map<String, List<SysDicModel4Page>> DICSMAPS = new ConcurrentHashMap<String, List<SysDicModel4Page>>();


@PostConstruct  //项目启动时会执行这个方法加载数据
public void load(){
System.out.println("--------------------------------------------------------------");
List<SysDicType> types = typeMapper.queryByAll();
List<SysDic> dics = this.getMapper().queryByAll();

List<String> typeCodes = new ArrayList<String>();

for(SysDicType type :types){
typeCodes.add(type.getType_code());
}

//装配DICS
for(String type_code: typeCodes){
Map<String,String> dicMap = new HashMap<String,String>();
List<SysDic> removeDic = new ArrayList<SysDic>();
for(SysDic dic: dics){
if(type_code.equals(dic.getType_code())){
dicMap.put(dic.getData_code(), dic.getData_name());
removeDic.add(dic);
}
}
dics.removeAll(removeDic);
DICS.put(type_code, dicMap);
}
for(String type_code: typeCodes){
List<SysDic> sysDicblist = getMapper().getAvailSysDicByTypeCode(type_code);
List<SysDicModel4Page> list = new ArrayList<SysDicModel4Page>();
if(null !=sysDicblist &&!sysDicblist.isEmpty()){
SysDicModel4Page page = null ;
for(SysDic temp : sysDicblist){
page = new SysDicModel4Page();
page.setId(temp.getId());
page.setData_code(temp.getData_code());
page.setData_name(temp.getData_name());
list.add(page);
}
DICSMAPS.put(type_code, list);
}else{
DICSMAPS.put(type_code,  new ArrayList<SysDicModel4Page>());
}
}
}


        //调用查询使用
public static List<SysDicModel4Page> getListByDICSMPS(String type_code){
List<SysDicModel4Page> lists=new ArrayList<SysDicModel4Page>();
lists = DICSMAPS.get(type_code);
return lists;
}
public static Map<String, String> getDICSByType(String type_code){
Map<String, String> map = DICS.get(type_code);
return map;
}
public static String getDICS(String type_code,String data_code){
Map<String,String> map = DICS.get(type_code);
if(map==null || map.isEmpty()){
return "";
}
String data_name = DICS.get(type_code).get(data_code);
return data_name;
}

@Autowired
private SysDicMapper<SysDic> mapper;

@Autowired
private SysDicTypeMapper<SysDicType> typeMapper;


private static BeanCopier M2B = BeanCopier.create(SysDicModel.class,
SysDic.class, false);


private static BeanCopier B2M = BeanCopier.create(SysDic.class,
SysDicModel.class, false);


@Override
public void add(SysDicModel type) throws Exception {
try{
getMapper().add(transferM2B(type));

//重刷缓存dic
DICS =  new ConcurrentHashMap<String,Map<String,String>>();
load();

}catch(Exception e){
LogUtils.errorLog("添加数据字典时出现错误,e={}",new Object[]{ e});
}
}


public void updateBySelective(SysDicModel t) {
try{
t.setModi_date(new Timestamp(new Date().getTime()));
getMapper().updateBySelective(transferM2B(t));
//重刷缓存dic
DICS =  new ConcurrentHashMap<String,Map<String,String>>();
load();

}catch(Exception e){
LogUtils.errorLog("数据字典【updateBySelective】时出现错误,e={}",new Object[]{ e});
}
}



@Override
public void update(SysDicModel type) throws Exception {
try{
type.setModi_date(new Timestamp(new Date().getTime()));
getMapper().update(transferM2B(type));
//重刷缓存dic
DICS =  new ConcurrentHashMap<String,Map<String,String>>();
load();

}catch(Exception e){
LogUtils.errorLog("修改数据字典时出现错误,e={}",new Object[]{ e});
}
}



@Override
public List<SysDicModel> queryByAll() {
return transferB2M4ListForSysDic(mapper.queryByAll());
}




/*
* (non-Javadoc)

* @see
* com.anzhi.heifer.service.sys.impl.ISysMenuService#delete(java.lang.Object
* [])
*/
@Override
public void delete(Object[] ids) throws Exception {

try{
// 删除关联关系
for (Object id : ids) {
getMapper().delete(id);
}

//重刷缓存dic
DICS =  new ConcurrentHashMap<String,Map<String,String>>();
load();

}catch(Exception e){
LogUtils.errorLog("删除数据字典时出现错误,e={}",new Object[]{ e});
}
}


public SysDicMapper<SysDic> getMapper() {
return mapper;
}

public SysDicTypeMapper<SysDicType> getTypeMapper(){
return typeMapper;
}


@Override
public void deleteByTypeCode(String typeCode) {
mapper.deleteByTypeCode(typeCode);
//重刷缓存dic
DICS =  new ConcurrentHashMap<String,Map<String,String>>();
load();


}


public SysDic transferM2B(SysDicModel m) {
SysDic b = new SysDic();


M2B.copy(m, b, null);


return b;
}
/**
* sysDic专用的转换
* @param b
* @return
*/
public SysDicModel transferB2MForSysDic(SysDic b) {
SysDicModel m = new SysDicModel();
B2M.copy(b, m, null);
String status_lable = this.getDataNameByCode(DictionaryConstants.TYPE_CODE_AVAILORFORBID, m.getStatus());
m.setStatus_lable(status_lable);
return m;
}

public SysDicModel transferB2M(SysDic b) {
SysDicModel m = new SysDicModel();
B2M.copy(b, m, null);
return m;
}

/**
* sysDic专用的转换(避免循环回调)
* @param blist
* @return
*/
public List<SysDicModel> transferB2M4ListForSysDic(List<SysDic> blist) {
List<SysDicModel> mlist = new ArrayList<SysDicModel>();
List<SysDicModel> dicList = getAvailSysDicByTypeCode(DictionaryConstants.TYPE_CODE_AVAILORFORBID);
Map<String,String> data1 = new HashMap<String,String>();
for(SysDicModel dic :dicList){
data1.put(dic.getData_code(), dic.getData_name());
}

for (SysDic b : blist) {
SysDicModel m = new SysDicModel();
B2M.copy(b, m, null);
m.setStatus_lable(data1.get(m.getStatus().toString()));
mlist.add(m);
}
return mlist;
}

public List<SysDicModel> transferB2M4List(List<SysDic> blist) {
List<SysDicModel> mlist = new ArrayList<SysDicModel>();

for (SysDic b : blist) {
SysDicModel m = new SysDicModel();
B2M.copy(b, m, null);
mlist.add(m);
}
return mlist;
}


@Override
public List<SysDicModel> queryByList(SysDicModel model) throws Exception {
Integer rowCount = queryByCount(model);
model.getPager().setRowCount(rowCount);
List<SysDic> blist=getMapper().queryByList(transferM2B(model));
return transferB2M4ListForSysDic(blist);
}


@Override
public SysDicModel queryById(Object id) throws Exception {
return transferB2MForSysDic(getMapper().queryById(id));
}


@Override
public int queryByCount(SysDicModel model) throws Exception {
return getMapper().queryByCount(transferM2B(model));
}


@Override
public List<SysDicModel> getAvailSysDicByTypeCode(String type_code) {
List<SysDic> sysDicblist = getMapper().getAvailSysDicByTypeCode(type_code);
return transferB2M4List(sysDicblist);
}

@Override
public String getDataNameByCode(String typeCode, Object DataCode) {
SysDic dic = new SysDic();
dic.setType_code(typeCode);
dic.setData_code(DataCode.toString());
String dataName = getMapper().getDataNameByDic(dic);
return dataName;
}


/* (非 Javadoc) 
* <p>Title: getAvailSysDicByTypeCode4Page</p> 
* <p>Description: </p> 
* @param type_code
* @return 
* @see com.anzhi.heifer.service.sys.ISysDicService#getAvailSysDicByTypeCode4Page(java.lang.String) 
*/
@Override
public List<SysDicModel4Page> getAvailSysDicByTypeCode4Page(String type_code) {
List<SysDic> sysDicblist = getMapper().getAvailSysDicByTypeCode(type_code);
List<SysDicModel4Page> list = new ArrayList<SysDicModel4Page>();
if(null !=sysDicblist &&!sysDicblist.isEmpty()){
SysDicModel4Page page = null ;
for(SysDic temp : sysDicblist){
page = new SysDicModel4Page();
page.setId(temp.getId());
page.setData_code(temp.getData_code());
page.setData_name(temp.getData_name());
list.add(page);
}

}
return list;
}



Spring Boot项目启动时数据库中的数据缓存Map,可以使用Spring Boot提供的ApplicationRunner或CommandLineRunner接口,在项目启动完成后执行指定的逻辑。 具体实现步骤如下: 1. 创建一个缓存类,用于缓存数据库中的数据: ```java @Component public class DataCache { private Map<Long, Object> cache = new HashMap<>(); public void put(Long id, Object data) { cache.put(id, data); } public Object get(Long id) { return cache.get(id); } public Map<Long, Object> getAll() { return Collections.unmodifiableMap(cache); } } ``` 2. 创建一个数据加载类,实现ApplicationRunner或CommandLineRunner接口,并在其实现的run方法中将数据库中的数据缓存Map中: ```java @Component public class DataLoadRunner implements ApplicationRunner { @Autowired private DataCache dataCache; @Autowired private DataSource dataSource; @Override public void run(ApplicationArguments args) throws Exception { try (Connection conn = dataSource.getConnection()) { String sql = "SELECT id, data FROM table"; try (PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { while (rs.next()) { Long id = rs.getLong("id"); Object data = rs.getObject("data"); dataCache.put(id, data); } } } } } ``` 在这个例子中,我们使用了Spring Boot提供的DataSource来获取数据库连接,然后使用JDBC API将数据数据库中查询出来,并存储至DataCache中。 3. 在Spring Boot启动类中添加注解@EnableScheduling,开启定时任务功能,以便在数据发生变化时,能够及时更新缓存。 ```java @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这样,在Spring Boot项目启动完成后,数据就会被缓存Map中,并可以通过DataCache在整个应用程序中访问。如果数据发生变化,可以通过定时任务重新加载数据缓存中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值