这一篇主要是redis操作工具类以及基本配置文本储存

首先我们需要定义一个redisUtil去操作底层redis数据库:

 package com.lcc.cache.redis;

 import java.util.Date;
import java.util.Map; import org.joda.time.LocalDate;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback; public class RedisUtil {
private RedisTemplate<String, Object> redisTemplate; public Map<Object, Object> getHashValue(String key) {
return redisTemplate.opsForHash().entries(key);
} public <V> void setHashValue(String key, String hashKey, V value, Date date) {
if (date == null) {
date = LocalDate.now().plusDays(1).toDate();
}
Date expire = date;
redisTemplate.executePipelined(new SessionCallback<Object>() {
@Override
public <String, V> Object execute(RedisOperations<String, V> operations) throws DataAccessException {
operations.opsForHash().put((String) key, hashKey, value.toString());
operations.expireAt((String) key, expire);
return null;
}
});
} public void setHashValue(String key, Map<Object, Object> values, Date date) {
if (date == null) {
date = LocalDate.now().plusDays(1).toDate();
}
Date expire = date;
redisTemplate.executePipelined(new SessionCallback<Object>() {
@Override
public <String, V> Object execute(RedisOperations<String, V> operations) throws DataAccessException {
for (Object hashKey : values.keySet()) {
operations.opsForHash().put((String) key, hashKey, values.get(hashKey).toString());
operations.expireAt((String) key, expire);
}
return null;
}
});
} public void delete(String key) {
redisTemplate.delete(key);
} public RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate;
} public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
} }

上面是基本的增删查操作,以及设置key的过期时间,该工具类是基于hash操作的。

工具类有了,我们自然要有一个业务逻辑去具体处理这些数据,接下来我们就建一个RedisService:

 package com.lcc.cache.redis;

 import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime; import com.alibaba.dubbo.common.utils.StringUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcc.api.dto.TruckCacheDto; public class RedisService { private RedisUtil redisUtil; private int cacheDay = 1; private String prefix = "truckCache:"; public TruckCacheDto getTruckById(String id) throws JsonParseException, JsonMappingException, IOException {
Map<Object, Object> map = redisUtil.getHashValue(prefix + id);
map.put("id", id);
TruckCacheDto dto = new TruckCacheDto();
prepareDto(map, dto);
return dto;
} private void prepareDto(Map<Object, Object> map, TruckCacheDto dto)
throws JsonParseException, JsonMappingException, IOException {
dto.setId(map.get("id").toString());
if (map.get("lat") != null) {
dto.setLat(Double.parseDouble(map.get("lat").toString()));
}
if (map.get("lng") != null) {
dto.setLng(Double.parseDouble(map.get("lng").toString()));
}
if (map.get("temp") != null) {
ObjectMapper co = new ObjectMapper();
String temp = map.get("temp").toString();
List tList = co.readValue(temp, List.class);
List<Double> tempList = new ArrayList();
if (tList == null) {
tList = new ArrayList();
}
for (Object o : tList) {
if (o != null) {
tempList.add(new BigDecimal(o.toString()).doubleValue());
}
}
dto.setTempList(tempList);
}
if (map.get("time") != null) {
dto.setTime(new Date(Long.valueOf(map.get("time").toString())));
}
if (map.get("address") != null) {
dto.setAddress(map.get("address").toString());
}
} public void setLocation(String id, Double lat, Double lng, String address) {
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("lat", lat);
map.put("lng", lng);
map.put("time", LocalDateTime.now().toDate().getTime());
if (StringUtils.isNotEmpty(address)) {
map.put("address", address);
}
redisUtil.setHashValue(prefix + id, map, getExpireDate());
} public <T> void setTemp(String id, List<T> tempList) throws JsonProcessingException {
Map<Object, Object> map = new HashMap<Object, Object>();
ObjectMapper co = new ObjectMapper();
String temp = co.writeValueAsString(tempList);
map.put("temp", temp);
map.put("time", LocalDateTime.now().toDate().getTime());
redisUtil.setHashValue(prefix + id, map, getExpireDate());
} public <T> void setTempAndLocation(String id, Double lat, Double lng, List<T> tempList, String address)
throws JsonProcessingException {
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("lat", lat);
map.put("lng", lng);
ObjectMapper co = new ObjectMapper();
String temp = co.writeValueAsString(tempList);
map.put("temp", temp);
map.put("time", LocalDateTime.now().toDate().getTime());
if (StringUtils.isNotEmpty(address)) {
map.put("address", address);
}
redisUtil.setHashValue(prefix + id, map, getExpireDate());
} public void delete(String id) {
redisUtil.delete(prefix + id);
} private Date getExpireDate() {
return LocalDate.now().plusDays(cacheDay).toDate();
} public RedisUtil getRedisUtil() {
return redisUtil;
} public void setRedisUtil(RedisUtil redisUtil) {
this.redisUtil = redisUtil;
} public int getCacheDay() {
return cacheDay;
} public void setCacheDay(int cacheDay) {
this.cacheDay = cacheDay;
} }

此时,我们的一个service就写好了,我们在接口层面或者service层面可以随时调用这个RedisService了。

很显然,有了上面的工具类和service还是不够了,我们需要在xml文件里面去配置,因为我们是基于spring的,可以建一个applicationContext_redisCache.xml.

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd"> <bean class="com.lcc.cache.redis.RedisService" id="redisService">
<property name="redisUtil" ref="redisUtil"/>
<property name="cacheDay" value="${truckCache.redis.cacheDay}"/>
</bean> <bean class="com.lcc.cache.redis.RedisUtil" id="redisUtil">
<property name="redisTemplate" ref="truckkCacheRedisJdkSerializationTemplate"/>
</bean> <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 id="truckCacheRedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${truckCache.redis.host}" p:port="${truckCache.redis.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> </beans>

此时我们的xml配置就完成了,这里是配置一些redis数据库配置和注入类。

到此我们还差一个数据,就是redis服务器数据,我们可以建一个properties文件,这样子方便我们对项目的数据进行修改,redis.properties:

truckCache.redis.host = localhost
truckCache.redis.port = 6379
truckCache.redis.cacheDay = 1

我们的RedisService在springxml文件里配置完成了,在接口层面我们可以利用spring框架的自动注入功能注入RedisService了,进而对redis数据库进行各种操作了。

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

  1. spring+redis实例(二)

    这一篇redis实例是基于序列化储存-(写入对象,读取对象) 在spring+redis(一)中我们介绍了在spring中怎么去操作储存redis,基于string的储存,今天我们介绍一下redis基 ...

  2. spring redis入门

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

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

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

  4. 使用CacheCloud管理Redis实例

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

  5. spring+redis 集群下的操作

    文章就是记录一下工作当中的用到的点,与测试方法以备用,会不断更新. 配置文件spring-redis.xml: <?xml version="1.0" encoding=&q ...

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

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

  7. 深入理解Spring Redis的使用 (一)、Spring Redis基本使用

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

  8. spring+redis实现缓存

    spring + redis 实现数据的缓存 1.实现目标 通过redis缓存数据.(目的不是加快查询的速度,而是减少数据库的负担) 2.所需jar包 注意:jdies和commons-pool两个j ...

  9. spring得到实例和new一个实例,哪个快?

    spring配置的bean是默认单例,那么在程序中,得到一个实例一定比创建一个实例的速度快,也更加省资源.今天实际测试的时候发现,new 一个对象比spring得到一个对象快多了.后面自己又加了个单例 ...

随机推荐

  1. Spring Controller RequestMapping

    不同的Controller,可以标记相同的RequestMapping 但是精确到函数上时,不可以标记相同的RequestMapping构成完成相同的请求路径,如果标记,运行会报错,提示有相同的路径, ...

  2. Spring后台,通过name取值

    表单中,有同名控件(text/hidden/checkbox.......)的情况下,采用getParameterValues("name"):String[] 表单中,只有一个n ...

  3. python环境下安装opencv库的方法

    注意:安装opencv之前需要先安装numpy,matplotlib等 一.安装方法 方法一.在线安装 1.先安装opencv-python pip install opencv-python --u ...

  4. Spring Boot教程(二十七)整合Spring Security

    在这一节,我们将对/hello页面进行权限控制,必须是授权用户才能访问.当没有权限的用户访问后,跳转到登录页面. 添加依赖 在pom.xml中添加如下配置,引入对Spring Security的依赖. ...

  5. JavaWeb_使用dom4j解析、生成XML文件

    dom4j 官网 xml解析DOM文档对象模型(树形结构) DOM方式解析:把xml文档加载到内存形成树形结构,可以进行增删改的操作 Learn   使用dom4j解析文件"NewFile. ...

  6. 分布式-信息方式-ActiveMQ的Destination高级特性3

    虚拟destination用来创建逻辑destination,客户端可以通过它来生产和消费消息,它会把消息映射到物理destination. ActiveMQ支持2种方式: 1:虚拟主题(Virtua ...

  7. C++入门经典-例3.22-循环嵌套打印三角形

    1:代码如下: // 3.22.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <iostream> usin ...

  8. http服务配置和apache

    CentOS 6 httpd 程序环境 记录了httpd的主进程编号:    主程序文件: /usr/sbin/httpd /usr/sbin/httpd.worker /usr/sbin/http ...

  9. Shell执行脚本

    Shell作用是解释执行用户的命令,用户输入一条命令,Shell就解释执行这一条,这种方式称为交互式,但还有另一种执行命令的方式称为批处理方式,用户事先写一个Shell脚本,Shell可以一次把这些命 ...

  10. scrum例会报告+燃尽图02

    此作业要求参见:https://edu.cnblogs.com/campus/nenu/2019fall/homework/9955 一.小组情况 组长:贺敬文组员:彭思雨 王志文 位军营 徐丽君队名 ...