在项目开发过程中,针对并发量较大、查询频率较高的数据,如果还是直接查询数据库,会使数据库压力过大造成系统响应速度下降。可以选择使用缓存技术对这些常用数据进行缓存,在查询这些数据时先从缓存中查,如果查询到数据,直接返回不用查询数据库。Redis就是一个优秀的nosql数据缓存技术。
Redis是nosql非关系型数据库,数据结构以key-value的形式,每个key对应唯一一个value,同时由于Redis数据是运行在内存中的,查询效率非常高,但是又因为是直接占用内存资源的,一般只对高频率的数据进行缓存。
在项目中使用Redis缓存原因:
1.减轻数据库压力
2.提高查询效率
Redis的数据结构为key-value,其中value支持五种格数数据:
1.字符串(strings)
2.字符串列表(lists)
3.字符串集合(sets)
4.有序字符串集合(sorted sets)
5.哈希(hashes)
在项目中使用Redis缓存流程:
1.查询时先从缓存中查询
2.缓存中如果没有数据再从数据库查询,并将数据保存进缓存
3.如果缓存中查询到数据,直接返回,不再需要查询数据库
数据的缓存同步问题
如果对数据进行了缓存,当查询数据时,如果缓存中有数据则直接返回缓存数据不会查询数据,当数据库数据改变时就有可能出现数据不一致的问题。可以考虑在每次修改数据库的时候同时将对应的缓存数据删除,这样重新查询的时候就会查询数据库并缓存(针对数据量比较小的情况)。
spring整合Redis
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- redis交给spring管理 -->
<!-- 创建JedisPoolConfig对象 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="1000"></property>
<property name="maxIdle" value="20"></property>
</bean>
<!-- 单机版连接池交给spring管理 -->
<bean class="redis.clients.jedis.JedisPool">
<constructor-arg name="poolConfig" ref="poolConfig"></constructor-arg>
<constructor-arg name="host" value="192.168.66.66"></constructor-arg>
<constructor-arg name="port" value="6379"></constructor-arg>
</bean>
<!-- 集群交给spring管理 -->
<!-- <bean class=&