背景

随着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="${redis.softMinEvictableIdleTimeMillis}" />
		<!-- 连接用尽后,调用者是否需要等待 设置为true时,maxWaitMillis才会起作用 -->
		<property name="blockWhenExhausted" value="${redis.blockWhenExhausted}" />
		<!-- 连接用尽后,调用者的最大等待时间,-1表示永不超时 -->
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
		<!-- 向连接池获取连接时是否进行有效性检测,无效连接会被移除,业务量大时建议关闭 -->
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />

		<!-- 开启空闲资源监测,建议开启 -->
		<property name="testWhileIdle" value="${redis.testWhileIdle}" />
		<!-- 空闲资源检测周期 -->
		<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" />
		<!-- 空闲资源检测时,每次的采样数量 设置为-1表示对所有连接做空闲检测 -->
		<property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}" />
		<!-- 连接池中资源最小空闲时间,达到值后空闲连接将被移除 -->
		<property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" />
	</bean>

	<!-- 连接工厂 -->
	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="poolConfig" ref="jedisPoolConfig" />
		 <property name="hostName" value="${redis.host}" />
		 <property name="port" value="${redis.port}" />
		 <property name="password" value="${redis.password}" />
	</bean>

	<!-- redis缓存 jackon序列化 -->
	<bean id="redisJacksonTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
		<!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! -->
		<property name="keySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<property name="valueSerializer">
			<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
		</property>
		<property name="hashKeySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<property name="hashValueSerializer">
			<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
		</property>
		<!-- 事务支持 默认关闭,若开启事务,会出现错误,需要手动解决 -->
		<property name="enableTransactionSupport" value="false" />
	</bean>

</beans>

通过将 RedisTemplate 注入到 spring bean 中即可操作 redis;

集群版
<?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="${redis.softMinEvictableIdleTimeMillis}" />
		<!-- 连接用尽后,调用者是否需要等待 设置为true时,maxWaitMillis才会起作用 -->
		<property name="blockWhenExhausted" value="${redis.blockWhenExhausted}" />
		<!-- 连接用尽后,调用者的最大等待时间,-1表示永不超时 -->
		<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
		<!-- 向连接池获取连接时是否进行有效性检测,无效连接会被移除,业务量大时建议关闭 -->
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />

		<!-- 开启空闲资源监测,建议开启 -->
		<property name="testWhileIdle" value="${redis.testWhileIdle}" />
		<!-- 空闲资源检测周期 -->
		<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" />
		<!-- 空闲资源检测时,每次的采样数量 设置为-1表示对所有连接做空闲检测 -->
		<property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}" />
		<!-- 连接池中资源最小空闲时间,达到值后空闲连接将被移除 -->
		<property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" />
	</bean>
	
	<!-- 集群配置 -->
	<bean id="redisClusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
		<property name="maxRedirects" value="3" />
	    <!-- 节点配置 -->
	    <property name="clusterNodes">
	        <set>
	            <bean class="org.springframework.data.redis.connection.RedisClusterNode">
	                <constructor-arg name="host" value="${redis.host1}" />
	                <constructor-arg name="port" value="${redis.port1}" />
	            </bean>
	            <bean class="org.springframework.data.redis.connection.RedisClusterNode">
	                <constructor-arg name="host" value="${redis.host2}" />
	                <constructor-arg name="port" value="${redis.port2}" />
	            </bean>
	            <bean class="org.springframework.data.redis.connection.RedisClusterNode">
	                <constructor-arg name="host" value="${redis.host3}" />
	                <constructor-arg name="port" value="${redis.port3}" />
	            </bean>
	            <bean class="org.springframework.data.redis.connection.RedisClusterNode">
	                <constructor-arg name="host" value="${redis.host4}" />
	                <constructor-arg name="port" value="${redis.port4}" />
	            </bean>
	            <bean class="org.springframework.data.redis.connection.RedisClusterNode">
	                <constructor-arg name="host" value="${redis.host5}" />
	                <constructor-arg name="port" value="${redis.port5}" />
	            </bean>
	            <bean class="org.springframework.data.redis.connection.RedisClusterNode">
	                <constructor-arg name="host" value="${redis.host6}" />
	                <constructor-arg name="port" value="${redis.port6}" />
	            </bean>
	        </set>
	    </property>
	</bean>

	<!-- 连接工厂 -->
	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<!-- 集群配置 -->
		<constructor-arg index="0" ref="redisClusterConfig" />
		<!-- 连接池配置 -->
		<constructor-arg index="1" ref="jedisPoolConfig" />
	</bean>

	<!-- redis缓存 jackon序列化 -->
	<bean id="redisJacksonTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory" />
		<!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! -->
		<property name="keySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<property name="valueSerializer">
			<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
		</property>
		<property name="hashKeySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<property name="hashValueSerializer">
			<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
		</property>
		<!-- 事务支持 默认关闭,若开启事务,会出现错误,需要手动解决 -->
		<property name="enableTransactionSupport" value="false" />
	</bean>

</beans>

通过将 RedisTemplate 注入到 spring bean 中即可对 redis集群进行操作;

来源:https://www.cnblogs.com/herokevin/p/15824381.html