一、添加文件 redis.properties
代码:
redis.host=127.0.0.1 redis.port=6379 redis.timeout=-1 redis.maxIdle=100 #在jedis连接池中,最大的idle状态(空闲状态)下的jedis实例的个数 redis.minIdle=8 #在jedis连接池中,最小的idle状态(空闲状态)下的jedis实例的个数 redis.maxTotal=100 #最大连接数 redis.testOnBorrow=true #在borrow一个redis实例的时候,是否进行验证操作 #如果为true,则得到的实例是一个可用的实例 redis.testOnReturn=false #在return一个redis实例的时候,是否进行验证操作 #如果为true,则得到的实例是一个可用的实例 #一般会提前验证,所以为false,增加性能app
二、pom.xml添加
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.8.1.RELEASE</version> </dependency>
三、applicaltionContext.xml
<!--加载redis配置文件--> <context:property-placeholder location="classpath:redis.properties" /> <!-- jedis 配置 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="minIdle" value="${redis.minIdle}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}" /> <property name="testOnReturn" value="${redis.testOnReturn}"/> </bean> <!-- redis服务器中心 --> <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="poolConfig" ref="poolConfig" /> <property name="port" value="${redis.port}" /> <property name="hostName" value="${redis.host}" /> <property name="password" value="${redis.pass}" /> <property name="timeout" value="${redis.timeout}" /> </bean> <!-- redis操作模板,面向对象的模板 --> <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> <property name="connectionFactory" ref="connectionFactory" /> <!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 --> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> </property> </bean>
四、测试 ->>上代码(配置完上面的代码后,就直接可以使用测试代码)
public class RedisTest { public static JedisPool jedisPool=new JedisPool();//jedis连接池 public static void main(String[] args) { Jedis jedis=jedisPool.getResource();//获取jedis实例 jedis.set("b","a"); jedis.setex("c",30,"redis"); jedisPool.returnBrokenResource(jedis); jedisPool.destroy(); System.out.println("end"); } }