java SpringBoot中,查一次表加载到缓存中,避免多次查表

基于google的这个jar实现

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import com.amarsoft.hub.api.model.AccountInfo;
import com.amarsoft.logmonitor.common.Constants;
import com.amarsoft.logmonitor.utils.LogMonitorUtils;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

@Component
public class AccountInfoCache {
    
    private final Logger LOGGER = LoggerFactory.getLogger(AccountInfoCache.class);
    
    private LoadingCache<String, AccountInfo> accountInfoCache;
    
    @Autowired
    @Qualifier("accountJdbcTemplate")
    private JdbcTemplate readJdbcTemplate;

    
    @PostConstruct
    public void init() {
        accountInfoCache = CacheBuilder.newBuilder()
                .expireAfterWrite(1, TimeUnit.DAYS)//这句话的意思可能是每查一次缓存持续的时间为1天
                .build(new CacheLoader<String, AccountInfo>() {
                    @Override
                    public AccountInfo load(String bankId) throws Exception {
                        AccountInfo accountInfo = loadByBankId(bankId);
                        return accountInfo == null ? new AccountInfo() : accountInfo;
                    }
                    
                });
        
        //加载全部帐号信息
        List<AccountInfo> accountInfos = loadAll();
        if (accountInfos != null && accountInfos.size() > 0) {
            LOGGER.info("初始化帐号信息到缓存中");
            accountInfos.stream().forEach(accountInfo -> accountInfoCache.put(accountInfo.getBankId(), accountInfo));
        }
    }

    

    public String getCustomerName(String bankId) {
        try {
            return accountInfoCache.get(bankId).getName();
        } catch (Exception e) {
            LOGGER.error("根据bankId="+bankId+"获取名字时出现差异",e);
            LOGGER.info(LogMonitorUtils.putMonitorMsg(Constants.LOG_LEVEL_ERROR, "根据bankId="+bankId+"获取名字时出现差异", e.getMessage()));
            return "";
        }
    }
    
    private List<AccountInfo> loadAll() {
        String sql = "select bankId,name from customer";
        LOGGER.info("SQL:{}",sql);
        return readJdbcTemplate.query(sql, new AccountInfoRowMapper());
    }

    
    private AccountInfo loadByBankId(String bankId) {
        String sql = "select bankId,name from customer where bankId = ?";
        LOGGER.info("SQL:{}",sql);
        List<AccountInfo> records = readJdbcTemplate.query(sql, new AccountInfoRowMapper(),bankId);
        
        return records == null || records.isEmpty() ? null : records.get(0);
    }

    
    private class AccountInfoRowMapper implements RowMapper<AccountInfo> {

        @Override
        public AccountInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setBankId(rs.getString("bankId"));
            accountInfo.setName(rs.getString("name"));
            
            return accountInfo;
        }
    }
}

最终的调用方式:

@Autowired
 private AccountInfoCache accountInfoCache;

String accountDescribe = accountInfoCache.getCustomerName(accountId);

猜你喜欢

转载自blog.csdn.net/John_Kry/article/details/86543611