本文主要是介绍spring + Jedis 的方式使用缓存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
spring + Jedis 的方式使用缓存
jar 包
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.8.1</version> </dependency>
配置文件
config.properties
redis.host=127.0.0.1 redis.port=6379 redis.password=foobared redis.timeout=60000 redis.database=0 redis.pool.maxActive=300 redis.pool.maxIdle=100 redis.pool.maxWait=2000
spring-jedis.xml
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><context:property-placeholder location="classpath:config.properties"/><bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"><property name="maxTotal" value="${redis.pool.maxActive}" /><property name="maxIdle" value="${redis.pool.maxIdle}" /><property name="maxWaitMillis" value="${redis.pool.maxWait}" /><property name="testOnBorrow" value="false" /><property name="testOnReturn" value="false" /></bean><bean id="jedisPool" class="redis.clients.jedis.JedisPool"><constructor-arg name="poolConfig" ref="jedisPoolConfig" /><constructor-arg name="host" value="${redis.host}" /><constructor-arg name="port" value="${redis.port}" type="int" /><constructor-arg name="timeout" value="${redis.timeout}" type="int" /><constructor-arg name="password" value="${redis.password}" /><constructor-arg name="database" value="${redis.database}" type="int" /></bean> </beans>
测试
package com.susq.jedis;import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool;/** * @author susq * @since 2018-05-04-10:17 */ @Slf4j @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(value = "classpath:spring-jedis.xml") public class JedisTest {@Autowiredprivate JedisPool jedisPool;@Testpublic void setTest() {Jedis jedis = jedisPool.getResource();String codeReply = jedis.set("key2","hello jedis one");jedis.close();log.info(codeReply);}@Testpublic void getTest() {Jedis jedis = jedisPool.getResource();String value = jedis.get("key2");log.info(value);}@Testpublic void del() {Jedis jedis = jedisPool.getResource();jedis.set("key2","hello jedis one");log.info(jedis.get("key2"));jedis.del("key2");log.info(jedis.get("key2"));} }
参考: JedisAPI
这篇关于spring + Jedis 的方式使用缓存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!