这一篇主要是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数据库进行各种操作了。

最新文章

  1. ajax前后端数据交互简析
  2. Web APi之过滤器执行过程原理解析【二】(十一)
  3. 去掉移动端页面 input, textarea, button, a 标签获取焦点时显示的黑影
  4. 杭电ACM1003
  5. shell 脚本,提取文件中的内容
  6. java嵌套类
  7. ESLint – 可扩展的 JavaScript &amp; JSX 校验工具
  8. 活学活用,webapi HTTPBasicAuthorize搭建小型云应用的实践
  9. firebug下载时出现there was an error loading firebug
  10. DATASNAP倒底能承受多大的负载能力
  11. mysql各种日志对应的配置项
  12. Oracle EBS-SQL (SYS-21):sys_用户名与人员对应关系查询.sql
  13. Ultimus BPM 金融与证券行业应用解决方案
  14. linux系统设置cpu孤立
  15. 如何给win7自带的截图工具设置快捷键
  16. pymysql的使用
  17. selenium3 TestNG 介绍与配置
  18. nginx uwsgi django 配置
  19. 面试题-linux基础
  20. Spring AOP Capabilities and Goal

热门文章

  1. JSONArray排序和倒转
  2. CentOS 7 各个版本的区别
  3. Make文件(一)
  4. /static/fonts/SIMYOU.TTF’ 字体
  5. GC类型以及不同类型GC的搭配 1
  6. Android 6.0动态权限申请
  7. npm安装 syscall access
  8. .slideUp()
  9. tps抖动
  10. asp.net 获取服务器及客户端的相关信息