您的位置:首页 > 数据库 > Redis

redis和Spring的整合

2016-07-19 16:18 561 查看
第一步:导入依赖

<dependency>
<span style="white-space:pre">	</span><groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.0</version>
</dependency>
第二步:写applicationContext-redis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> 
<!-- 定义连接池配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大连接数 -->
<property name="maxTotal" value="${redis.maxTotal}"></property>
</bean>
<!-- 定义分片式连接池 -->
<bean class="redis.clients.jedis.ShardedJedisPool" destroy-method="close">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<!-- 配置集群的节点信息 -->
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.node1.ip}"/>
<constructor-arg index="1" value="${redis.node1.port}"/>
</bean>
<!-- <bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.node2.ip}"/>
<constructor-arg index="1" value="${redis.node2.port}"/>
</bean> -->
</list>
</constructor-arg>
</bean>
</beans>
第三步:写redis.properties

redis.maxTotal=100
redis.node1.ip=127.0.0.1
redis.node1.port=6379


第四步:spring配置文件了把redis.properties添加上

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 允许JVM参数覆盖 -->
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<!-- 忽略没有找到的资源文件 -->
<property name="ignoreResourceNotFound" value="true" />
<!-- 配置资源文件 -->
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:upload.properties</value>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>


第五步:写个接口,用于拓展

public interface Function<E,T> {
public T callback(E e);
}
第六步:写通用service

@Service
public class RedisService {

@Autowired
private ShardedJedisPool shardedJedisPool;

private <T> T execute(Function<ShardedJedis, T> fun) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = shardedJedisPool.getResource();
return fun.callback(shardedJedis);
} finally {
if (null != shardedJedis) {
// 关闭,检测连接是否有效,有效则放回到连接池中,无效则重置状态
shardedJedis.close();
}
}
}

/**
* 设置值
*
* @param key
* @param value
* @return
*/
public String set(final String key, final String value) {
return this.execute(new Function<ShardedJedis, String>() {
@Override
public String callback(ShardedJedis jedis) {
return jedis.set(key, value);
}
});
}

/**
* 获取值
*
* @param key
* @return
*/
public String get(final String key) {
return this.execute(new Function<ShardedJedis, String>() {
@Override
public String callback(ShardedJedis e) {
return e.get(key);
}
});
}

/**
* 删除
*
* @param key
* @return
*/
public Long del(final String key) {
return this.execute(new Function<ShardedJedis, Long>() {
@Override
public Long callback(ShardedJedis e) {
return e.del(key);
}
});
}

/**
* 设置生存时间
*
* @param key
* @return
*/
public Long expire(final String key, final Integer seconds) {
return this.execute(new Function<ShardedJedis, Long>() {
@Override
public Long callback(ShardedJedis e) {
return e.expire(key, seconds);
}
});
}

/**
* 设置值以及生存时间,单位为秒
*
* @param key
* @param value
* @param seconds
* @return
*/
public String set(final String key, final String value, final Integer seconds) {
return this.execute(new Function<ShardedJedis, String>() {
@Override
public String callback(ShardedJedis jedis) {
String result = jedis.set(key, value);
jedis.expire(key, seconds);
return result;
}
});
}

}


第七步:使用:注意添加缓存的原则:不能影响正常的业务逻辑执行

1.从缓存中命中,如果命中,直接返回,如果没有命中,程序继续往下执行

2.需要将执行的结果写入到缓存中

例子:

package com.taotao.manage.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.bean.ItemCatData;
import com.taotao.common.bean.ItemCatResult;
import com.taotao.manage.pojo.ItemCat;

@Service
public class ItemCatService extends BaseService<ItemCat> {
@Autowired
private RedisService redisService;

// ObjectMapper这里用于序列号和反序列化
private static final ObjectMapper MAPPER = new ObjectMapper();

// redis定义一个key,规则:项目名_模块名_业务名
private static final String REDIS_KEY = "TAOTAO_MANAGE_ITEMCAT_WEB_ALL";

// 定义缓存的时间,单位秒
private static final Integer REDIS_TIME = 60 * 60 * 24 * 30;

/**
* 全部查询,并且生成树状结构
*/
public ItemCatResult queryAllToTree() {
try {
String cacheData = this.redisService.get(REDIS_KEY);
if (StringUtils.isNotEmpty(cacheData)) { // 如果命中
// 反系列化
ItemCatResult itemCatResult = MAPPER.readValue(cacheData, ItemCatResult.class);
return itemCatResult;
}
} catch (Exception e) {
e.printStackTrace();
}
ItemCatResult result = new ItemCatResult();
// 得到所有数据
List<ItemCat> itemCats = super.queryAll();
// 声明一个map,用于存储itemCats,key为parentId,value为数据集合
Map<Long, List<ItemCat>> itemCatMap = new HashMap<Long, List<ItemCat>>();
for (ItemCat itemCat : itemCats) {
if (!itemCatMap.containsKey(itemCat.getParentId())) {
itemCatMap.put(itemCat.getParentId(), new ArrayList<ItemCat>());
}
itemCatMap.get(itemCat.getParentId()).add(itemCat);
}
// 封装一级对象
List<ItemCat> itemCatList1 = itemCatMap.get(0L);
for (ItemCat itemCat : itemCatList1)
af14
{
ItemCatData itemCatData = new ItemCatData();
itemCatData.setUrl("/products/" + itemCat.getId() + ".html");
itemCatData.setName("<a href='" + itemCatData.getUrl() + "'>" + itemCat.getName() + "</a>");
result.getItemCats().add(itemCatData);
if (!itemCat.getIsParent()) {
continue;
}

// 封装二级对象
List<ItemCat> itemCatList2 = itemCatMap.get(itemCat.getId());
List<ItemCatData> itemCatData2 = new ArrayList<ItemCatData>();
itemCatData.setItems(itemCatData2);
for (ItemCat itemCat2 : itemCatList2) {
ItemCatData id2 = new ItemCatData();
id2.setName(itemCat2.getName());
id2.setUrl("/products/" + itemCat2.getId() + ".html");
itemCatData2.add(id2);
if (itemCat2.getIsParent()) {
// 封装三级对象
List<ItemCat> itemCatList3 = itemCatMap.get(itemCat2.getId());
List<String> itemCatData3 = new ArrayList<String>();
id2.setItems(itemCatData3);
for (ItemCat itemCat3 : itemCatList3) {
itemCatData3.add("/products/" + itemCat3.getId() + ".html|" + itemCat3.getName());
}
}
}
// 最多返回14个一级类目
if (result.getItemCats().size() >= 14) {
break;
}
}
try {
// 将结果写入到缓存
this.redisService.set(REDIS_KEY, MAPPER.writeValueAsString(result), REDIS_TIME);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redis