spring + redis 实例(一)

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

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

 1 package com.lcc.cache.redis;
 2 
 3 import java.util.Date;
 4 import java.util.Map;
 5 
 6 import org.joda.time.LocalDate;
 7 import org.springframework.dao.DataAccessException;
 8 import org.springframework.data.redis.core.RedisOperations;
 9 import org.springframework.data.redis.core.RedisTemplate;
10 import org.springframework.data.redis.core.SessionCallback;
11 
12 public class RedisUtil {
13     private RedisTemplate<String, Object> redisTemplate;
14 
15     public Map<Object, Object> getHashValue(String key) {
16         return redisTemplate.opsForHash().entries(key);
17     }
18 
19     public <V> void setHashValue(String key, String hashKey, V value, Date date) {
20         if (date == null) {
21             date = LocalDate.now().plusDays(1).toDate();
22         }
23         Date expire = date;
24         redisTemplate.executePipelined(new SessionCallback<Object>() {
25             @Override
26             public <String, V> Object execute(RedisOperations<String, V> operations) throws DataAccessException {
27                 operations.opsForHash().put((String) key, hashKey, value.toString());
28                 operations.expireAt((String) key, expire);
29                 return null;
30             }
31         });
32     }
33 
34     public void setHashValue(String key, Map<Object, Object> values, Date date) {
35         if (date == null) {
36             date = LocalDate.now().plusDays(1).toDate();
37         }
38         Date expire = date;
39         redisTemplate.executePipelined(new SessionCallback<Object>() {
40             @Override
41             public <String, V> Object execute(RedisOperations<String, V> operations) throws DataAccessException {
42                 for (Object hashKey : values.keySet()) {
43                     operations.opsForHash().put((String) key, hashKey, values.get(hashKey).toString());
44                     operations.expireAt((String) key, expire);
45                 }
46                 return null;
47             }
48         });
49     }
50 
51     public void delete(String key) {
52         redisTemplate.delete(key);
53     }
54 
55     public RedisTemplate<String, Object> getRedisTemplate() {
56         return redisTemplate;
57     }
58 
59     public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
60         this.redisTemplate = redisTemplate;
61     }
62 
63 }

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

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

  1 package com.lcc.cache.redis;
  2 
  3 import java.io.IOException;
  4 import java.math.BigDecimal;
  5 import java.util.ArrayList;
  6 import java.util.Date;
  7 import java.util.HashMap;
  8 import java.util.List;
  9 import java.util.Map;
 10 
 11 import org.joda.time.LocalDate;
 12 import org.joda.time.LocalDateTime;
 13 
 14 import com.alibaba.dubbo.common.utils.StringUtils;
 15 import com.fasterxml.jackson.core.JsonParseException;
 16 import com.fasterxml.jackson.core.JsonProcessingException;
 17 import com.fasterxml.jackson.databind.JsonMappingException;
 18 import com.fasterxml.jackson.databind.ObjectMapper;
 19 import com.lcc.api.dto.TruckCacheDto;
 20 
 21 public class RedisService {
 22 
 23     private RedisUtil redisUtil;
 24 
 25     private int cacheDay = 1;
 26 
 27     private String prefix = "truckCache:";
 28 
 29     public TruckCacheDto getTruckById(String id) throws JsonParseException, JsonMappingException, IOException {
 30         Map<Object, Object> map = redisUtil.getHashValue(prefix + id);
 31         map.put("id", id);
 32         TruckCacheDto dto = new TruckCacheDto();
 33         prepareDto(map, dto);
 34         return dto;
 35     }
 36 
 37     private void prepareDto(Map<Object, Object> map, TruckCacheDto dto)
 38             throws JsonParseException, JsonMappingException, IOException {
 39         dto.setId(map.get("id").toString());
 40         if (map.get("lat") != null) {
 41             dto.setLat(Double.parseDouble(map.get("lat").toString()));
 42         }
 43         if (map.get("lng") != null) {
 44             dto.setLng(Double.parseDouble(map.get("lng").toString()));
 45         }
 46         if (map.get("temp") != null) {
 47             ObjectMapper co = new ObjectMapper();
 48             String temp = map.get("temp").toString();
 49             List tList = co.readValue(temp, List.class);
 50             List<Double> tempList = new ArrayList();
 51             if (tList == null) {
 52                 tList = new ArrayList();
 53             }
 54             for (Object o : tList) {
 55                 if (o != null) {
 56                     tempList.add(new BigDecimal(o.toString()).doubleValue());
 57                 }
 58             }
 59             dto.setTempList(tempList);
 60         }
 61         if (map.get("time") != null) {
 62             dto.setTime(new Date(Long.valueOf(map.get("time").toString())));
 63         }
 64         if (map.get("address") != null) {
 65             dto.setAddress(map.get("address").toString());
 66         }
 67     }
 68 
 69     public void setLocation(String id, Double lat, Double lng, String address) {
 70         Map<Object, Object> map = new HashMap<Object, Object>();
 71         map.put("lat", lat);
 72         map.put("lng", lng);
 73         map.put("time", LocalDateTime.now().toDate().getTime());
 74         if (StringUtils.isNotEmpty(address)) {
 75             map.put("address", address);
 76         }
 77         redisUtil.setHashValue(prefix + id, map, getExpireDate());
 78     }
 79 
 80     public <T> void setTemp(String id, List<T> tempList) throws JsonProcessingException {
 81         Map<Object, Object> map = new HashMap<Object, Object>();
 82         ObjectMapper co = new ObjectMapper();
 83         String temp = co.writeValueAsString(tempList);
 84         map.put("temp", temp);
 85         map.put("time", LocalDateTime.now().toDate().getTime());
 86         redisUtil.setHashValue(prefix + id, map, getExpireDate());
 87     }
 88 
 89     public <T> void setTempAndLocation(String id, Double lat, Double lng, List<T> tempList, String address)
 90             throws JsonProcessingException {
 91         Map<Object, Object> map = new HashMap<Object, Object>();
 92         map.put("lat", lat);
 93         map.put("lng", lng);
 94         ObjectMapper co = new ObjectMapper();
 95         String temp = co.writeValueAsString(tempList);
 96         map.put("temp", temp);
 97         map.put("time", LocalDateTime.now().toDate().getTime());
 98         if (StringUtils.isNotEmpty(address)) {
 99             map.put("address", address);
100         }
101         redisUtil.setHashValue(prefix + id, map, getExpireDate());
102     }
103 
104     public void delete(String id) {
105         redisUtil.delete(prefix + id);
106     }
107 
108     private Date getExpireDate() {
109         return LocalDate.now().plusDays(cacheDay).toDate();
110     }
111 
112     public RedisUtil getRedisUtil() {
113         return redisUtil;
114     }
115 
116     public void setRedisUtil(RedisUtil redisUtil) {
117         this.redisUtil = redisUtil;
118     }
119 
120     public int getCacheDay() {
121         return cacheDay;
122     }
123 
124     public void setCacheDay(int cacheDay) {
125         this.cacheDay = cacheDay;
126     }
127 
128 }

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

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

 1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:aop="http://www.springframework.org/schema/aop"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:p="http://www.springframework.org/schema/p"
 6        xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 7        xmlns:rabbit="http://www.springframework.org/schema/rabbit"
 8        xsi:schemaLocation="http://www.springframework.org/schema/aop
 9              http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
10              http://www.springframework.org/schema/beans 
11              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
12              http://www.springframework.org/schema/context
13              http://www.springframework.org/schema/context/spring-context-3.0.xsd
14              http://www.springframework.org/schema/jee 
15              http://www.springframework.org/schema/jee/spring-jee-3.0.xsd 
16              http://www.springframework.org/schema/tx 
17              http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
18              http://www.springframework.org/schema/rabbit 
19              http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
20 
21 
22     <bean class="com.lcc.cache.redis.RedisService" id="redisService">
23         <property name="redisUtil" ref="redisUtil"/>
24         <property name="cacheDay" value="${truckCache.redis.cacheDay}"/>
25     </bean>
26 
27      <bean class="com.lcc.cache.redis.RedisUtil" id="redisUtil">
28         <property name="redisTemplate" ref="truckkCacheRedisJdkSerializationTemplate"/>
29     </bean>
30 
31    <bean class="org.springframework.data.redis.core.RedisTemplate"
32           id="truckkCacheRedisJdkSerializationTemplate" p:connection-factory-ref="truckCacheRedisConnectionFactory">
33         <property name="keySerializer">
34             <bean
35                     class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
36         </property>
37         <property name="valueSerializer">
38             <bean
39                     class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
40         </property>
41     </bean>
42 
43     <bean id="truckCacheRedisConnectionFactory"
44           class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
45           p:host-name="${truckCache.redis.host}" p:port="${truckCache.redis.port}">
46           <constructor-arg index="0" ref="jedisPoolConfig"/>
47     </bean>
48 
49     <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
50         <property name="maxTotal" value="60"/>
51         <property name="maxIdle" value="15"/>
52         <property name="testOnBorrow" value="true"/>
53     </bean>
54 
55 </beans>

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

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

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

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

原文地址:https://www.cnblogs.com/cc-java/p/6598918.html