spring boot 集成 redis

阅读更多

spring boot 集成redis,本人选用xml文件的形式,由于spring boot 得简单易用,网上多用注解的形式集成redis

,话不多说,上代码

1、首先配置文件redis-config.properties,初始化redis的一些参数,包括端口、密码等

redis.maxIdle=10

redis.maxTotal=100

redis.database=2

redis.timeout=3000

redis.host=127.0.0.1

redis.password=

redis.port=6379

 2、xml配置文件redis-config.xml

 

     

 

class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 

destroy-method="destroy">

 

class="org.springframework.data.redis.serializer.StringRedisSerializer"/>

class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>

 

 

       

   

 

3、RedisUtil工具类

 

@Component

public class RedisUtil {

 

private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);

 

private RedisTemplate redisTemplate;

 

/**

* 批量删除对应的key

* @param keys

*/

public void remove(final String... keys) {

for(String key : keys) {

remove(key);

}

}

 

/**

* 删除缓存中相应额key

* @param key

*/

public void remove(String key) {

if(exists(key)) {

redisTemplate.delete(key);

}

}

 

/**

* 判断是否存在相应的key

* @param key

* @return

*/

public boolean exists(String key) {

return redisTemplate.hasKey(key);

}

 

/**

* 批量删除key

* @param pattern

*/

public void removePattern(final String pattern) {

Set keys = redisTemplate.keys(pattern);

if(keys.size() > 0) {

redisTemplate.delete(keys);

}

}

 

/**

* 读取缓存

* @param key

* @return

*/

public Object get(final String key) {

Object result = null;

ValueOperations< Serializable, Object> operations = redisTemplate.opsForValue();

result = operations.get(key);

return result;

}

 

/**

* 写入缓存

* @param key

* @param value

* @return

*/

public boolean set(final String key, Object value) {

boolean result = false;

try {

ValueOperations operations = redisTemplate.opsForValue();

operations.set(key, value);

result = true;

}catch (Exception e) {

logger.error("set cache error", e);

}

return result;

}

 

/**

* 写入缓存时间,单位秒

* @param key

* @param value

* @param expireTime

* @return

*/

public boolean set(final String key, Object value, Long expireTime) {

boolean result = false;

try {

ValueOperations operations = redisTemplate.opsForValue();

operations.set(key, value);

redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);

result = true;

}catch (Exception e) {

logger.error("set cache error", e);

}

return result;

}

 

/**

* 以增量的方式将long值存储在变量中。

* @param key

* @param delta

* @return

*/

public long increment(final String key, long delta) {

return redisTemplate.opsForValue().increment(key, delta);

}

 

public void setRedisTemplate(RedisTemplate redisTemplate) {

this.redisTemplate = redisTemplate;

}

 

这样spring boot就集成了redis,打开redis服务器,就可以使用了。大笑

你可能感兴趣的:(spring,boot,java,redis)