缓存管理 通常在项目当中,需要对数据库进行crud,对于大量查询、低频次修改的数据, 可以使用缓存来减少数据库的查询次数,提高程序的响应性能。 缓存的策略, 分布式环境下,缓存和数据库的数据一致性问题如何解决? 1:我们一般只对数据字典表,那些高频率查询、低频率更新的数据进行缓存 2:我们目前缓存的策略,查询时候先查询缓存,再查询数据库,如果没有再添加缓存 增删改的时候,先更新数据库,再删除缓存, 但是这种场景也会出现缓存和数据库数据不一致问题, 如果真有必要,nginx使用iphash, tomcat可以使用jvm的内存队列 blockingqueue,将用户增删改的操作有序的存储起来, 通过线程池顺序的执行操作,就可以避免数据不一致问题 缓存的本质其实就是一个map<查询条件,查询结构> 常用的缓存中间件 ehcache memercached redis mogodb 缓存又分为本地缓存(配合nginx+ipHash)和分布式缓存 分布式缓存解决方案 主流使用redis来解决 spring-cache 框架 可以整合各种缓存容器
开发步骤:
1:引入spring-context(spring-cache)
2:redis相关的,redis.properties 配置spring-redis.xml
前两个步骤在session分离已经整合过了。:https://blog.csdn.net/weixin_42275175/article/details/100096142
3:spring-cache的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<cache:annotation-driven/>
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<!-- 这里可以配置多个缓存的实现,spring cache只提供了cache接口
缓存的实现,需要自己手动完成
-->
<bean class="com.xiupeilian.carpart.Cache.RedisCache">
<property name="redisTemplate" ref="redisTemplate" />
<!-- name对应的名称要在类或方法的注解中使用 -->
<property name="name" value="canglaoshi"/>
</bean>
</set>
</property>
</bean>
</beans>
4:自定义缓存实现类(实现spring-cache下面的cache接口)
5:使用注解来定义缓存策略(通常情况下缓存定义在service级别)
注意事项:将来被缓存的数据model,必须得实现序列化接口
详细看这里:https://www.cnblogs.com/wangfg/p/9476332.html
@cache
@cacheput
@cacheEvict