一. redis的安装和调试就不做介绍,这样的文章已经很多了
二. redis在Java开发中的一些实用心得
言归正传:
redis集成在spring框架中
需要的jar包 :
spring-data-redis-1.5.1.RELEASE.jar
jedis-2.6.0.jar
spring系列jar包最好用4.0.9及以上
redis的xml文件:
applicationContext-redis.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true" />
<!-- Jedis 连接池配置-->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="minIdle" value="${redis.pool.minIdle}" />
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
</bean>
<!-- Jedis ConnectionFactory 数据库连接配置-->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<!-- <constructor-arg ref="sentinelConfig" /> -->
<property name="hostName" value="${redis.hostname}" />
<property name="port" value="${redis.port}" />
<!-- <property name="password" value="${redis.password}" /> -->
<property name="poolConfig" ref="jedisPoolConfig" />
</bean>
<bean id="redisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnectionFactory" >
<property name="keySerializer" ref="redisSerializer"/>
<property name="valueSerializer" ref="redisSerializer"/>
<property name="hashKeySerializer" ref="redisSerializer"/>
<property name="hashValueSerializer" ref="redisSerializer"/>
</bean>
</beans>
------------------------------------------------------------------------------
redis.properties 配置文件
#redis config
redis.pool.maxTotal=100
redis.pool.minIdle=20
redis.pool.maxIdle=50
redis.pool.testOnBorrow=true
#redis.hostname=
redis.hostname=127.0.0.1
redis.port=6379
redis.password=
示例:
主要作用为: redis是一种nosql数据库, redis存储数据的方式为key-value ,redis处理字符串更高效
不要再把关系型数据库的对象模型强塞入redis中,会导致存储空间使用率和处理效率低下,
如下展示 核心思想是 把Java中的对象 改造为hash存储 , list列表转换为set集合方式读取
同时 redis提供高效率的IO操作,单个数据操作对象最好不要超过1兆大小
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import cust.fav.vo.FavIn;
import cust.fav.vo.Info;
@Service
public class FavRedis {
private static Logger log = Logger.getLogger("REDIS_LOG");
@Resource
private RedisTemplate redisTemplate;
// 进行添加
@SuppressWarnings("unchecked")
public boolean addFav(FavIn FavIn) throws Exception {
boolean flag = true;
log.info("增加,开始");
String key4Set = InfoUtil4Redis.makeKey4Set(FavIn.getUserId());// 用户键
String key4Hash = InfoUtil4Redis.makeKey4Has(FavIn.getUserId(), FavIn.getId());
String key4Value = InfoUtil4Redis.makeKey4Value(FavIn.getId());
log.info("生成的KEY为:" + key4Set);
if (redisTemplate.opsForSet().isMember(key4Set, FavIn.getId())) {
flag = false;
//log.info("所有成员如下:" + redisTemplate.opsForSet().members(key4Set));
} else {
// 保存SET
redisTemplate.opsForSet().add(key4Set, FavIn.getId());
// 保存对象
redisTemplate.opsForHash().putAll(key4Hash, InfoUtil4Redis.makeMap(FavIn));
// 存储一个对象加1
redisTemplate.opsForValue().increment(key4Value, 1);
log.info("增加,完成");
}
return flag;
}
// 列表查询
@SuppressWarnings("unchecked")
public List qryFav(FavIn FavIn) throws Exception {
List<Info> InfoList = new ArrayList<Info>();
String key4Set = InfoUtil4Redis.makeKey4Set(FavIn.getUserId());// 用户键
Set Ids = redisTemplate.opsForSet().members(key4Set);
for (Iterator iterator = Ids.iterator(); iterator.hasNext();) {
Object IdTemp = (Object) iterator.next();
Info Result = doQryFavById(FavIn.getUserId(), IdTemp);
InfoList.add(Result);
}
return InfoList;
}
//单独查询功能
public Info qryFavById(FavIn FavIn) throws Exception {
return doQryFavById(FavIn.getUserId(), FavIn.getId());
}
private Info doQryFavById(String userId, Object Id) throws Exception {
String key4Hash = InfoUtil4Redis.makeKey4Has(userId, Id+"");;
List<String> Details = redisTemplate.opsForHash().multiGet(key4Hash, InfoUtil4Redis.makeCollections());
log.info("明细为:" + key4Hash);
Info Result = InfoUtil4Redis.buildBean(Details);
return Result;
}
// 更新信息
@SuppressWarnings("unchecked")
public void updateFav(FavIn FavIn) {
String key4Hash = InfoUtil4Redis.makeKey4Has(FavIn.getUserId(), FavIn.getId());
redisTemplate.opsForHash().put(key4Hash, "_label", FavIn.getLabel());
log.info("更新,完毕!");
}
// 取消
@SuppressWarnings("unchecked")
public void delFav(FavIn FavIn) throws Exception {
// boolean flag =true;
log.info("取消,开始");
String key4Set = InfoUtil4Redis.makeKey4Set(FavIn.getUserId());// 用户键
String key4Hash = InfoUtil4Redis.makeKey4Has(FavIn.getUserId(), FavIn.getId());
String key4Value = InfoUtil4Redis.makeKey4Value(FavIn.getId());
if (!redisTemplate.opsForSet().isMember(key4Set, FavIn.getId())) {
// flag =false;
throw new Exception("不存在!");
} else {
// 删除对象
redisTemplate.opsForSet().remove(key4Set, FavIn.getId());
redisTemplate.delete(key4Hash);
// 数量减一
redisTemplate.opsForValue().increment(key4Value, -1);
log.info("取消,完成");
}
// return flag;
}
}
public class InfoUtil4Redis {
//创建set键 作用与Java中的set功能类似
public static String makeKey4Set(String userId) {
return "usercenter::fav::Key4Set::" + userId;
}
//创建hash键 作用与Java中的hashmap功能类似 可以用来存储对象
public static String makeKey4Has(String userId, String Id) {
return "usercenter::fav::Key4Hash::" + userId +"::"+Id;
}
//创建value键
public static String makeKey4Value(String Id) {
return "usercenter::prod::"+Id;
}
}