这一篇redis实例是基于序列化储存-(写入对象,读取对象)

在spring+redis(一)中我们介绍了在spring中怎么去操作储存redis,基于string的储存,今天我们介绍一下redis基于序列化的储存。

平常在项目里面往数据库存贮的大多数是一个对象,因为我们好多都是面向对象开发。

下面的例子介绍了往redis数据库里面写入session对象:

1.既然是写入一个对象,我们肯定要有一个对象,下面是一个session class:

package com.lcc.api.dto.session;

import java.io.Serializable;
import java.util.Map; public class MobileSessionInfo extends SessionInfo implements Serializable { private static final long serialVersionUID = -9170869913976089130L; private Map<String, String> emails; public Map<String, String> getEmails() {
return emails;
} public void setEmails(Map<String, String> emails) {
this.emails = emails;
} @Override
public String toString() {
return new StringBuilder().append("{emails: ").append(emails).append("}").toString();
}
}
package com.lcc.api.dto.session;

import java.io.Serializable;

public abstract class SessionInfo implements Serializable {

    private static final long serialVersionUID = 6544973626519192604L;

    private String key;
// timestamp
private Long createdAt;
// unit: second
private Long expiryTime; public String getKey() {
return key;
} public void setKey(String key) {
this.key = key;
} public Long getCreatedAt() {
return createdAt;
} public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
} public Long getExpiryTime() {
return expiryTime;
} public void setExpiryTime(Long expiryTime) {
this.expiryTime = expiryTime;
} @Override
public String toString() {
return new StringBuilder().append("{key: ").append(key).append(", createdAt: ").append(createdAt)
.append(", expiryTime: ").append(expiryTime).append("}").toString();
}
}

2.接下来写一个service去操作写入session对象:

package com.lcc.service.app.impl;

import com.lcc.api.dto.session.MobileSessionInfo;
import com.lcc.service.BaseAuthorityService;
import com.lcc.service.app.DeviceService; import java.util.HashMap;
import java.util.Map; public class DeviceServiceImpl implements DeviceService { private BaseAuthorityService authorityService; private Long expiryTime = 24*60*60L; public void setAuthorityService(BaseAuthorityService authorityService) {
this.authorityService = authorityService;
} public void setExpiryTime(Long expiryTime) {
this.expiryTime = expiryTime;
} @Override
public void catchSession(String deviceId) {
MobileSessionInfo session = new MobileSessionInfo();
Map<String, String> emails = new HashMap<String, String>();
session.setKey(deviceId);
session.setEmails(emails);
session.setExpiryTime(expiryTime);
authorityService.saveSessionInfo(session);
}
}
package com.lcc.service;

import com.lcc.domain.enums.SessionCacheMode;
import com.lcc.api.dto.session.SessionInfo; public interface BaseAuthorityService { SessionInfo getSessionInfo(String sessionId); void saveSessionInfo(SessionInfo session); SessionCacheMode getCacheMode();
}
package com.lcc.api.domain.enums;

public enum SessionCacheMode {

    LOCAL(1), //
REDIS(2); private Integer value; SessionCacheMode(Integer value) {
this.value = value;
} public Integer getValue() {
return value;
} public static SessionCacheMode fromValue(Integer value) {
for (SessionCacheMode mode : values()) {
if (mode.getValue() == value) {
return mode;
}
}
return null;
}
}
package com.lcc.authority;

import com.google.common.collect.Maps;
import com.lcc.api.domain.enums.SessionCacheMode;
import com.lcc.api.dto.session.SessionInfo;
import com.lcc.logger.Logger;
import com.lcc.logger.LoggerFactory;
import com.lcc.service.BaseAuthorityService;
import org.joda.time.LocalDateTime;
import org.springframework.data.redis.core.RedisTemplate; import java.util.Date;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit; public class AuthorityService implements BaseAuthorityService { private static final Logger LOGGER = LoggerFactory.getLogger(AuthorityService.class); private static final String CAHCE_MODE_KEY = "cache-mode"; private RedisTemplate<String, SessionInfo> sessionTemplate; public void setSessionTemplate(RedisTemplate<String, SessionInfo> sessionTemplate) {
this.sessionTemplate = sessionTemplate;
} /**
* session global attributes
* <p>
* default open redis session cache mode
* </p>
*
*/
private static final ConcurrentMap<String, Object> BUCKETS = Maps.newConcurrentMap();
static {
BUCKETS.put(CAHCE_MODE_KEY, SessionCacheMode.REDIS);
} @Override
public SessionInfo getSessionInfo(String sessionId) {
LOGGER.info("get session {}, cache mode {}", sessionId, getCacheMode()); SessionInfo sessionInfo = null;
try {
sessionInfo = sessionTemplate.opsForValue().get(sessionId);
} catch (Exception e) {
LOGGER.error("get session from redis exception", e);
}
return sessionInfo;
} @Override
public void saveSessionInfo(SessionInfo session) {
session.setCreatedAt(LocalDateTime.now().toDate().getTime());
try {
sessionTemplate.opsForValue().set(session.getKey(), session);
sessionTemplate.expire(session.getKey(), session.getExpiryTime(), TimeUnit.SECONDS);
} catch (Exception e) {
LOGGER.error("H5 save session exception, open local cache mode", e);
}
} @Override
public SessionCacheMode getCacheMode() {
return (SessionCacheMode) BUCKETS.get(CAHCE_MODE_KEY);
}
}

3.基本的java class搞定了,然后看下spring配置文件:

<bean class="org.springframework.data.redis.core.RedisTemplate"
id="authorityCacheRedisJdkSerializationTemplate" p:connection-factory-ref="h5SessionRedisConnectionFactory">
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean
class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean> <bean id="h5SessionRedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.session.host}" p:port="${redis.session.port}">
<constructor-arg index="0" ref="jedisPoolConfig" />
</bean> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="60"/>
<property name="maxIdle" value="15"/>
<property name="testOnBorrow" value="true"/>
</bean>
<bean id="deviceService" class="com.opentrans.otms.service.xtt.impl.DeviceServiceImpl">
<property name="authorityService" ref="authorityService" />
<property name="expiryTime" value="${session.expiry.time}" />
</bean> <bean id="authorityService" class="com.opentrans.otms.authority.AuthorityService" >
<property name="sessionTemplate" ref="authorityCacheRedisJdkSerializationTemplate" />
</bean>

总结:redis序列化操作和文本操作最主要的区别是RedisTemplate里面两个属性的配置不同:

一个是keySerializer一个是valueSerializer(StringRedisSerializer|JdkSerializationRedisSerializer)

   <bean class="org.springframework.data.redis.core.RedisTemplate"
id="truckkCacheRedisJdkSerializationTemplate" p:connection-factory-ref="truckCacheRedisConnectionFactory">
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
</bean> <bean class="org.springframework.data.redis.core.RedisTemplate"
id="authorityCacheRedisJdkSerializationTemplate" p:connection-factory-ref="h5SessionRedisConnectionFactory">
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean
class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>

spring+redis实例(二)的更多相关文章

  1. spring + redis 实例(一)

    这一篇主要是redis操作工具类以及基本配置文本储存 首先我们需要定义一个redisUtil去操作底层redis数据库: package com.lcc.cache.redis; import jav ...

  2. springMVC+Hibernate4+spring整合实例二(实例代码部分)

    UserController.java 代码: package com.edw.controller; import java.io.IOException; import java.io.Print ...

  3. python3.4学习笔记(二十五) Python 调用mysql redis实例代码

    python3.4学习笔记(二十五) Python 调用mysql redis实例代码 #coding: utf-8 __author__ = 'zdz8207' #python2.7 import ...

  4. redis之(二十一)redis之深入理解Spring Redis的使用

    关于spring redis框架的使用,网上的例子很多很多.但是在自己最近一段时间的使用中,发现这些教程都是入门教程,包括很多的使用方法,与spring redis丰富的api大相径庭,真是浪费了这么 ...

  5. 使用CacheCloud管理Redis实例

    转载来源:http://www.ywnds.com/?p=10610 一.CacheCloud是什么? 最近在使用CacheCloud管理Redis,所以简单说一下,这里主要说一下我碰到的问题.Cac ...

  6. spring redis入门

    小二,上菜!!! 1. 虚拟机上安装redis服务 下载tar包,wget http://download.redis.io/releases/redis-2.8.19.tar.gz. 解压缩,tar ...

  7. redis 实例2 构建文章投票网站后端

    redis 实例2 构建文章投票网站后端   1.限制条件 一.如果网站获得200张支持票,那么这篇文章被设置成有趣的文章 二.如果网站发布的文章中有一定数量被认定为有趣的文章,那么这些文章需要被设置 ...

  8. 分布式缓存技术redis学习—— 深入理解Spring Redis的使用

    关于spring redis框架的使用,网上的例子很多很多.但是在自己最近一段时间的使用中,发现这些教程都是入门教程,包括很多的使用方法,与spring redis丰富的api大相径庭,真是浪费了这么 ...

  9. Spring Security4实例(Java config 版) —— Remember-Me

    本文源码请看这里 相关文章: Spring Security4实例(Java config版)--ajax登录,自定义验证 Spring Security提供了两种remember-me的实现,一种是 ...

随机推荐

  1. TTTTTTTTTTTTT 树的直径 Codeforces Beta Round #14 (Div. 2) D. Two Paths

    tiyi:给你n个节点和n-1条边(无环),求在这个图中找到 两条路径,两路径不相交,求能找的两条路径的长度的乘积最大值: #include <iostream> #include < ...

  2. codevs 5960 信使x

    题目描述 Description •战争时期,前线有n个哨所,每个哨所可能会与其他若干个哨所之间有通信联系.信使负责在哨所之间传递信息,当然,这是要花费一定时间的(以天为单位).指挥部设在第一个哨所. ...

  3. c++复习——一个小疑问

    C++中,子类为什么不能访问基类的private数据?     emmm  来自一个vegetable dog的疑问:   首先基类可以通过调用自身public成员函数来访问private 而子类又可 ...

  4. 1209F - Koala and Notebook

    这场比赛没打,看同学fst了,于是来看看. 这道题看似简单,但是没想清楚细节真的不太行.像现在熬到十一点左右,脑子真的不行. 首先显然位数越小越好,因为每一位要比较,不如拆点.此时要拆成两条有向链(开 ...

  5. [AGC034D]Manhattan Max Matching:费用流

    前置姿势 \(k\)维空间内两点曼哈顿距离中绝对值的处理 戳这里:[CF1093G]Multidimensional Queries 多路增广的费用流 据说这个东西叫做ZKW费用流? 流程其实很简单, ...

  6. [BZOJ3611][Heoi2014]大工程(虚树上DP)

    3611: [Heoi2014]大工程 Time Limit: 60 Sec  Memory Limit: 512 MBSubmit: 2464  Solved: 1104[Submit][Statu ...

  7. Java 8 - Stream Collectors分组的例子

    1.分组依据,计数和排序 1.1按a分组List并显示它的总数. package com.mkyong.java8; import java.util.Arrays; import java.util ...

  8. 从a标签为什么不能包含div标签-了解HTML5元素分类与内容模型

    我们知道按新的 HTML 规范,已经不按 inline 和 block 来区分元素类型了.所以我们在a标签里面使用div标签时候会发现a标签并不能通过改变css盒子模型的方式将div元素包含. 元素分 ...

  9. DH加密算法

    http://blog.csdn.net/zbw18297786698/article/details/53609794

  10. idea maven sync Cannot resolve xxx 的解决方案

    经常会出现这种奇葩情况,提示找不到包 其实是因为网络波动或者突然断掉,导致包更新出现问题 直接去maven的仓库目录 找到不能找到的包 删掉相关目录 然后重新更新maven就行了 比如 直接去仓库目录 ...