前言

做过大型软件系统的同学都知道,随着系统数据越来越庞大,越来越复杂,随之带来的问题就是系统性能越来越差,尤其是频繁操作数据库带来的性能损耗更为严重。很多业绩大牛为此提出了众多的解决方案和开发了很多框架以优化这种频繁操作数据库所带来的性能损耗,其中,尤为突出的两个缓存服务器是Memcached和Redis。今天,我们不讲Memcached和Redis本身,这里主要为大家介绍Spring与Redis整合使用的相关内容,下面话不多说了,来一起看看详细的介绍吧。

方法如下

第一步,在项目中加入redis的pom代码:

redis.clients

jedis

2.6.0

第二步,spring中加载redis配置文件:applicationContext-redis.xml,内容如下

第三步,编写连接redis服务端的属性文件:redis.properties

redis.maxTotal=100

redis.node1.host=127.0.0.1

redis.node1.port=6379

第四步,编写redis的相关操作方法类,Function类和RedisService类:

Funcrion类:

package xx.service;
/**
* 为了抽取相同的操作代码
* @author yeying
*
Description:
*
Company:
* @date:2017年12月5日 下午9:02:44
*/
public interface Function {
public T callback(E e);
}
RedisService类:
package com.taotao.common.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
/**
* redis的相关操作
* @author yeying
*
Description:
*
Company:
* @date:2017年12月3日 下午2:11:47
*/
@Service
public class RedisService {
@Autowired(required=false) //需要再注入进去
private ShardedJedisPool shardedJedisPool;
private T execute(Function fun){
ShardedJedis shardedJedis = null;
try {
// 从连接池中获取到jedis分片对象
shardedJedis = shardedJedisPool.getResource();
// 从redis中获取数据
return fun.callback(shardedJedis);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != shardedJedis) {
// 关闭,检测连接是否有效,有效则放回到连接池中,无效则重置状态
shardedJedis.close();
}
}
return null;
}
/**
* 执行set操作
* @param key
* @param value
* @return
*/
public String set(final String key,final String value){
return this.execute(new Function() {
@Override
public String callback(ShardedJedis e) {
return e.set(key, value);
}
});
}
/**
* 执行set操作,并设置生存时间,单位为秒
* @param key
* @param value
* @param seconds
* @return
*/
public String set(final String key,final String value,final Integer seconds){
return this.execute(new Function() {
@Override
public String callback(ShardedJedis e) {
String str =e.set(key, value);
e.expire(key, seconds);
return str;
}
});
}
/**
* 执行get操作
* @param key
* @return
*/
public String get(final String key){
return this.execute(new Function() {
@Override
public String callback(ShardedJedis e) {
return e.get(key);
}
});
}
/**
* 执行set操作
* @param key
* @return
*/
public Long del(final String key){
return this.execute(new Function() {
@Override
public Long callback(ShardedJedis e) {
return e.del(key);
}
});
}
/**
* 设置生存时间,单位为秒
* @param key
* @param seconds
* @return
*/
public Long expire(final String key, final Integer seconds) {
return this.execute(new Function() {
@Override
public Long callback(ShardedJedis e) {
return e.expire(key, seconds);
}
});
}
}

第五步,启动redis服务,redis-server.exe,双击打开:

spring redis使用 spring结合redis_ide