Springdata-redis在项目中的使用

一、maven的配置

<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.0.3.RELEASE</version>
			<exclusions>
				<exclusion>
					<groupId>log4j</groupId>
					<artifactId>log4j</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.slf4j</groupId>
					<artifactId>slf4j-log4j12</artifactId>
				</exclusion>
			</exclusions>

		</dependency>

二、redis配置文件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:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
	http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
	http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
	http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"
	default-lazy-init="true">

	<description>Spring维护的使用redis用到的bean </description>

	
	<!-- redis -->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxActive" value="${redis.pool.maxActive}" />
		<property name="maxIdle" value="${redis.pool.maxIdle}" />
		<property name="maxWait" value="${redis.pool.maxWait}" />
		<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
	</bean>


	<bean id="connectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="${redis.ip}" />
		<property name="port" value="${redis.port}" />
		<property name="poolConfig" ref="jedisPoolConfig" />
		<property name="password" value="${redis.password}" />
	</bean>


	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="connectionFactory"></property>
		<property name="keySerializer">
			<bean
				class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<property name="hashKeySerializer">
			<bean
				class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<property name="valueSerializer">
			<bean
				class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
		</property>
		<property name="hashValueSerializer">
			<bean
				class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
		</property>
	</bean>
	
</beans>



redis.properties文件

redis.pool.maxActive = 1024 
redis.pool.maxIdle = 100
redis.pool.maxWait = 1000
redis.pool.testOnBorrow = true
redis.ip=47.92.110.33
redis.port=6379
redis.password=123


三、项目中的使用

RedisKeyUtils类
public class RedisKeyUtils {

	/** pop:usercenter:user:id **/
	public final static String split = ":";

	public final static String pop = "pop";

	public final static String usercenter = "uc";

	public final static String user = "user";
	public final static String userPartner = "userPartner";
	public final static String userBrowse = "userBrowse";
	public final static String userOnline = "userOnline";
	public final static String attr = "attr";
	public final static String sid = "sid";
	public final static String country = "country";
	public final static String city = "city";
	public final static String token = "token";
	public final static String vcode = "vcode";
	public final static String list = "list";
	

	/** 存储用户信息 **/
	public static String getUserInfo(long userId) {
		String key = getRedisKey(pop, usercenter, user, userId + "");
		return key;
	}

	/** 存储用户在线信息 **/
	public static String getUserOnline(long userId) {
		String key = getRedisKey(pop, usercenter, userOnline, userId + "");
		return key;
	}

	/** 存储用户人气信息 **/
	public static String getUserBrowse(long userId) {
		String key = getRedisKey(pop, usercenter, userBrowse, userId + "");
		return key;
	}

	/** 存储用户语伴信息 **/
	public static String getUserPartner(long userId) {
		String key = getRedisKey(pop, usercenter, userPartner, userId + "");
		return key;
	}

	/** 存储用户session信息 **/
	public static String getUserSession(long userId) {
		String key = getRedisKey(pop, usercenter, sid, userId + "");
		return key;
	}

	private static String getRedisKey(String... name) {
		StringBuffer sb = new StringBuffer();
		for (String str : name) {
			if (StringUtils.isNotBlank(str)) {
				sb.append(str);
				sb.append(split);
			}
		}
		sb = sb.deleteCharAt(sb.lastIndexOf(split));

		return sb.toString();

	}

	public static String getCountryNameKey(long id) {
		String key = getRedisKey(pop, country, id + "");
		return key;
	}

	public static String getCityNameKey(long id) {
		String key = getRedisKey(pop, city, id + "");
		return key;
	}

	public static String getUserTokenKey(Long id) {
		String key = getRedisKey(pop, user,token, id+"");
		return key;
	}

	public static String getVCodeKey(String str) {
		String key = getRedisKey(pop, vcode, str);
		return key;
	}

	public static String getLoginUserListKey() {
		String key = getRedisKey(pop, userOnline, list);
		return key;
	}

}
Service层的注入
@Service("userTokenService")
public class UserTokenServiceImpl implements UserTokenService {
	@Resource
	private RedisTemplate<String, String> redisTemplate;
存储用户token到redis中
public Map<String, Object> storeTokenToRedis(String token, Long userId) {
		logger.info("存储用户token信息,token:{},userId:{}", token, userId);
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String key = RedisKeyUtils.getUserTokenKey(userId);
			BoundValueOperations<String, String> options = redisTemplate
					.boundValueOps(key);
			options.set(token);
			options.expire(15, TimeUnit.DAYS);//设置token的有效期
			logger.info("存储用户token信息成功,token:{},userId:{}", token, userId);
		} catch (Exception e) {
			logger.error("存储用户token信息失败,exp:{}", e.toString());
			return ResponseUtils.returnFailMsg("操作失败");
		}
		return ResponseUtils.returnSuccessMsg(result);
	}
获取用户token信息
public Map<String, Object> getUserTokenById(Long userId) {
		logger.info("获取用户token信息,userId:{}", userId);
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			String token = getTokenStrByKey(userId);
			if (StringUtils.isBlank(token)) {
				logger.info("没有找到用户[{}]的token信息", userId);
				return ResponseUtils.returnFailMsg("1052");
			}
			result.put("token", token);
			logger.info("获取用户token信息成功,userId:{}", userId);
		} catch (Exception e) {
			logger.error("获取用户token信息失败,exp:{}", e.toString());
			return ResponseUtils.returnFailMsg("操作失败");
		}
		return ResponseUtils.returnSuccessMsg(result);
	}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值