spring + redis 实例(一)
这一篇主要是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 实例(一)的更多相关文章
- spring+redis实例(二)
这一篇redis实例是基于序列化储存-(写入对象,读取对象) 在spring+redis(一)中我们介绍了在spring中怎么去操作储存redis,基于string的储存,今天我们介绍一下redis基 ...
- spring redis入门
小二,上菜!!! 1. 虚拟机上安装redis服务 下载tar包,wget http://download.redis.io/releases/redis-2.8.19.tar.gz. 解压缩,tar ...
- 分布式缓存技术redis学习—— 深入理解Spring Redis的使用
关于spring redis框架的使用,网上的例子很多很多.但是在自己最近一段时间的使用中,发现这些教程都是入门教程,包括很多的使用方法,与spring redis丰富的api大相径庭,真是浪费了这么 ...
- 使用CacheCloud管理Redis实例
转载来源:http://www.ywnds.com/?p=10610 一.CacheCloud是什么? 最近在使用CacheCloud管理Redis,所以简单说一下,这里主要说一下我碰到的问题.Cac ...
- spring+redis 集群下的操作
文章就是记录一下工作当中的用到的点,与测试方法以备用,会不断更新. 配置文件spring-redis.xml: <?xml version="1.0" encoding=&q ...
- redis之(二十一)redis之深入理解Spring Redis的使用
关于spring redis框架的使用,网上的例子很多很多.但是在自己最近一段时间的使用中,发现这些教程都是入门教程,包括很多的使用方法,与spring redis丰富的api大相径庭,真是浪费了这么 ...
- 深入理解Spring Redis的使用 (一)、Spring Redis基本使用
关于spring redis框架的使用,网上的例子很多很多.但是在自己最近一段时间的使用中,发现这些教程都是入门教程,包括很多的使用方法,与spring redis丰富的api大相径庭,真是浪费了这么 ...
- spring+redis实现缓存
spring + redis 实现数据的缓存 1.实现目标 通过redis缓存数据.(目的不是加快查询的速度,而是减少数据库的负担) 2.所需jar包 注意:jdies和commons-pool两个j ...
- spring得到实例和new一个实例,哪个快?
spring配置的bean是默认单例,那么在程序中,得到一个实例一定比创建一个实例的速度快,也更加省资源.今天实际测试的时候发现,new 一个对象比spring得到一个对象快多了.后面自己又加了个单例 ...
随机推荐
- cdh-完整
安装包 CLOUDERA管理安装包 http://archive.cloudera.com/cm5/cm/5/ http://archive.cloudera.com/cm5/cm/5/clouder ...
- POJ 2195 一人一房 最小费用流 建图 水题
Going Home Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 21010 Accepted: 10614 Desc ...
- Codeforces Round #303 (Div. 2) D. Queue 水题贪心
题目: 题意:给你n个数值,要求排列这个序列使得第k个数值的前K-1个数的和>=第k个数值的个数尽可能多: #include <iostream> #include <cstd ...
- 翻译一篇英文文章,主要是给自己看的——在ASP.NET Core Web Api中如何刷新token
原文地址 :https://www.blinkingcaret.com/2018/05/30/refresh-tokens-in-asp-net-core-web-api/ 先申明,本人英语太菜,每次 ...
- 第十一周Java学习总结。
java UI 图形界面知识梳理: ATM: 在整个AWT包中提供的所有工具类主要分为以下3种. (1)组件:Component. (2)容器:Container. (3)布局管理器:LayoutMa ...
- 190707Python-MySQL
一.Python连接MySQL import pymysql conn = pymysql.connect(host='192.168.100.4', port=3306, user='dongfei ...
- laravel中事件的监听和订阅
一.前言 更新员工部门主管的时候,需要重新更新一下缓存,这个会比较耗时.所以计划放到队列中来执行.后来想了想,其实用一下事件监听也能实现.人家都说好,然是我也没感觉到有什么好的. 二.正文 1. 在p ...
- C++构造函数调用虚函数的后果
#include <iostream> class cx { public: virtual void func() { std::cout << "func&quo ...
- mesh之孔洞检测
mesh之孔洞检测 图1 检测孔洞点 图2 检测孔洞点 图3 检测孔洞点 图4 细节
- Vue复杂路由器的实现
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...