目录
只言片语
单机版
创建redis连接池的配置文件
spring整合redis(使用JedisPool)
分布式版
创建redis连接池的配置文件
spring整合redis(使用SharedJedisPool)
只言片语
Spring整合Redis,无非就是将手动创建Jedis对象的过程交给Spring来创建,并且使用Spring的IoC和DI在需要JedisPool的地方进行注入,然后获得Jedis对象,再进行操作。
下面会对单机版的Redis,以及Redis集群分别进行配置。
单机版
单机版,是指redis服务器只有一台,这个时候配置redis,是通过host+port来访问redis服务器。
创建redis连接池的配置文件
连接池配置文件名为redis_pool.properties,位于classpath目录下,内容如下:
redis_maxTotal=30 redis_maxIdle=15 redis_minIdle=5 redis_ip=127.0.0.1 redis_port=6379 redis_timeout=2000 redis_database=0
Spring整合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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="cn.ganlixin.test"></context:component-scan> <!-- 读取redis pool的配置文件 --> <context:property-placeholder location="classpath:redis_pool.properties" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="${redis_maxTotal}"></property> <property name="minIdle" value="${redis_minIdle}"></property> <property name="maxIdle" value="${redis_maxIdle}"></property> </bean> <bean id="jedisPool" class="redis.clients.jedis.JedisPool"> <constructor-arg name="poolConfig" ref="jedisPoolConfig"></constructor-arg> <constructor-arg name="host" value="${redis_host}"></constructor-arg> <constructor-arg name="port" value="${redis_port}"></constructor-arg> <constructor-arg name="timeout" value="${redis_timeout}"></constructor-arg> <constructor-arg name="database" value="${redis_database}"></constructor-arg> </bean> </beans>
测试
package cn.ganlixin.test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; @Component public class TestJedisPool { @Autowired private JedisPool jedisPool; public void doSomeAction() { // 获取jedis连接 Jedis jedis = jedisPool.getResource(); String name = jedis.get("name"); System.out.println(name); jedis.close(); } }
分布式版
分布式版是指Redis服务器有多台,而不是单独的一台Redis接收所有请求。