背景
随着Web项目的复杂程度逐渐增加,可能会涉及诸如高并发、海量数据查询的的业务场景也逐渐增多;若频繁的操作数据库,会触发数据库的I/O瓶颈,因此需要加入缓存,尽量减少直接操作数据库的频率和次数;同时在分布式系统中,分布式锁等应用场景也需要依赖redis等缓存数据库;redis作为nosql数据库的代表,拥有广泛的应用场景;
这里介绍下Spring集成redis,实现缓存:
准备工作:
1.引入依赖;
<!-- jedis 客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.2</version>
</dependency>
<!-- spring data redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.11.RELEASE</version>
</dependency>
2.定义 redis.proerties
文件,配置连接池相关参数;
# redis configuration
# 连接池配置
redis.maxTotal=30
redis.maxIdle=10
redis.softMinEvictableIdleTimeMillis=10000
redis.blockWhenExhausted=true
redis.maxWaitMillis=1500
redis.testOnBorrow=false
redis.testWhileIdle=true
redis.timeBetweenEvictionRunsMillis=30000
redis.numTestsPerEvictionRun=1024
redis.minEvictableIdleTimeMillis=180000
# 单机配置
redis.host=169.254.244.131
redis.port=6379
# 自己选择是否开启密码
redis.password=123456
# 集群配置
redis.host1=169.254.244.131
redis.port1=7001
redis.host2=169.254.244.131
redis.port2=7002
redis.host3=169.254.244.131
redis.port3=7003
redis.host4=169.254.244.131
redis.port4=7004
redis.host5=169.254.244.131
redis.port5=7005
redis.host6=169.254.244.131
redis.port6=7006
3.连接池配置引入spring上下文中;
<!--加载属性文件-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
<!-- 在多个spring配置文件中都配置了属性文件加载 必须设置为true -->
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
单机版
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 连接池配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大连接数 -->
<property name="maxTotal" value="${redis.maxTotal}" />
<!-- 最大空闲连接数 -->
<property name="maxIdle" value="${redis.maxIdle}" />
<!-- 连接空闲多久后释放, 当空闲时间>该值且空闲连接>最大空闲连接数时直接释放 -->
<property name="softMinEvictableIdleTimeMillis" value=&