题记:实现缓存大部分可以使用redis实现,简单、便捷,redis在针对应用部署多服务器是很好的,但如果针对单一服务器,内存缓存更好。
1、创建CacheLoader.java
import java.util.Iterator; import java.util.Map; /** * Created by Tisa on 2018/5/9. * 将数据库表记录加载到jvm */ public class CacheLoader<V,T> { /** * 将数据库中的记录加载到jvm缓存,使用Map存储 * * @param from 从数据库load出的记录 * @param to */ public void loadCache(Map<V, T> from, Map<V, T> to) { if (!from.isEmpty()) { Iterator<V> iterator = to.keySet().iterator(); while (iterator.hasNext()) { V key = iterator.next(); if (to.containsKey(key)) { to.remove(key); } } to.putAll(from); } else { to.clear(); } }
}
2、在springboot启动项目时加载进内存,创建ProvinceAppkeyAndSecretCache.java
import com.entity.ProvinceAppkeyAndAppsecret; import com.entity.ProvinceInfo; import com.mapper.ProvinceAppkeyAndSecretMapper; import com.mapper.ProvinceInfoMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * @author:yangwj */ @Component public class ProvinceAppkeyAndSecretCache { private static final Map<String, ProvinceAppkeyAndAppsecret> provinceAppkeyAndSecretCache = new ConcurrentHashMap<>(); @Autowired private ProvinceAppkeyAndSecretMapper provinceAppkeyAndSecretMapper; @PostConstruct public void init() { Map<String, ProvinceAppkeyAndAppsecret> provinceAppkeyAndSecretMap = loadProvinceInfo(); CacheLoader<String, ProvinceAppkeyAndAppsecret> loader = new CacheLoader<String, ProvinceAppkeyAndAppsecret>(); loader.loadCache(provinceAppkeyAndSecretMap, provinceAppkeyAndSecretCache); } private Map<String, ProvinceAppkeyAndAppsecret> loadProvinceInfo() { Map<String, ProvinceAppkeyAndAppsecret> map = new HashMap<>(); List<ProvinceAppkeyAndAppsecret> list = provinceAppkeyAndSecretMapper.selectAll(); if (list == null) { return Collections.emptyMap(); } Iterator<ProvinceAppkeyAndAppsecret> iterator = list.iterator(); while (iterator.hasNext()) { ProvinceAppkeyAndAppsecret next = iterator.next(); map.put(next.getAppkey(), next); } return map; } public ProvinceAppkeyAndAppsecret get(String appkey) { return provinceAppkeyAndSecretCache.get(appkey); } }
3、在controller中调用
@RestController @RequestMapping("Cache") public class CacheController extends BaseOrderController { private static final Logger LOGGER = LoggerFactory.getLogger(com.controller.CacheController.class); @Autowired private ProvinceAppkeyAndSecretCache provinceAppkeyAndSecretCache; @RequestMapping("/cache") public String orderRelationUpdateNotify(HttpServletRequest request) { String appKey = request.getParameter("appKey"); //从内存中获取 ProvinceAppkeyAndAppsecret provinceAppkeyAndAppsecret =provinceAppkeyAndSecretCache.get(appKey); }
}