Springdata-redis在项目中的使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>


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);



以上是关于Springdata-redis在项目中的使用的主要内容,如果未能解决你的问题,请参考以下文章

SpringData-Redis发布订阅自动重连分析

React re 在添加新项目时渲染数组中的所有项目,尽管所有项目都使用唯一键

thymeleaf在项目中的使用

thymeleaf在项目中的使用

如何在另一个项目中使用一个项目中的类

Lottie 动画在项目中的使用总结