基於JavaEE的SSM框架集成Redis

基於JavaEE的SSM框架集成redis,我的項目架構是SpringMVC+Spring+Mybatis 用maven管理 ,下面看代碼.

我的項目結構:(項目下載鏈接:https://pan.baidu.com/s/1dZCV0u4qDLg5mjZHqHerHg)


1. 在pom.xml文件引入redis依賴包

       <!-- redis集成spring -->
	<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.4.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.6.2</version>
        </dependency>
        <dependency>
	    <groupId>org.json</groupId>
	    <artifactId>json</artifactId>
	    <version>20150729</version>
	</dependency>
		
	<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
	<dependency>
	    <groupId>com.google.code.gson</groupId>
	    <artifactId>gson</artifactId>
	    <version>2.2.4</version>
	</dependency>

	<dependency>
	    <groupId>org.codehaus.jackson</groupId>
	    <artifactId>jackson-core-asl</artifactId>
	     <version>1.9.2</version>
	</dependency>
		
	<dependency>
	    <groupId>org.codehaus.jackson</groupId>
	    <artifactId>jackson-mapper-asl</artifactId>
	    <version>1.8.5</version>
	</dependency>
		
	<dependency>
	    <groupId>org.json</groupId>
	    <artifactId>org.json</artifactId>
	    <version>chargebee-1.0</version>
	</dependency>

2.web.xml中引入Redis的配置文件

<!-- 配置Redis環境 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext-redis.xml</param-value>
	</context-param>

3.redis配置文件applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
      default-autowire="byName" >
	<context:property-placeholder location="classpath*:/redis.properties" ignore-unresolvable="true"/> 
	
	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxTotal" value="${redis.maxActive}" />
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
      <property name="hostName" value="${redis.host}" />
      <property name="port" value="${redis.port}" />
      <property name="password" value="${redis.pass}" />
      <property name="poolConfig" ref="poolConfig" />
    </bean>
    
    <bean id="stringSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    <!-- 開啓事務,可以通過transcational註解控制 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="keySerializer" ref="stringSerializer" />
        <property name="enableTransactionSupport" value="true" />
    </bean>
    
</beans>

4.redis.properties配置文件 

redis.host=redis地址
redis.pass=密碼
redis.port=6379
redis.maxIdle=300
redis.maxActive=300
redis.maxTotal=600
redis.maxWait=1000
redis.testOnBorrow=true

5. Spring配置文件applicationContext.xml中引入Redis的配置文件

在項目啓動的時候會加載applicationContext-redis.xml文件,但是redis.properties需要配置,如下

    <bean id="config"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:/redis.properties</value>
			</list>
		</property>
    </bean>

6. 創建RedisService工具類,方便調用

package com.base.redis;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer;
import org.springframework.stereotype.Service;

import com.base.utils.StringUtils;

@Service
public class RedisService {

	private Logger LOG = LoggerFactory.getLogger(RedisService.class);

	@Autowired
	private List<RedisTemplate<String, String>> redisTemplateList;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	/**
	 * 從緩存中刪除指定的key
	 * @param keys
	 */
	public void del(final String... keys) {
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				redisTemplate.execute(new RedisCallback<Long>() {
					public Long doInRedis(RedisConnection connection) throws DataAccessException {
						long result = 0;
						for (int i = 0; i < keys.length; i++) {
							result = connection.del(keys[i].getBytes());
						}
						return result;
					}
				});

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 重緩存中刪除指定的key 模式匹配,效率低
	 * @param keys
	 */
	public void delByReg(final String... keys) {
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				redisTemplate.execute(new RedisCallback<Long>() {
					public Long doInRedis(RedisConnection connection) throws DataAccessException {
						long result = 0;
						for (int i = 0; i < keys.length; i++) {
							Set<byte[]> keyset = connection.keys((keys[i] + "*").getBytes());
							for (byte[] key : keyset) {
								result = connection.del(key);
							}
						}
						return result;
					}
				});

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 判斷一個鍵是否存在於緩存中
	 * @param key
	 * @return
	 */
	public boolean exists(final String key) {
		Boolean result = false;
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				result = (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
					public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
						return connection.exists(key.getBytes());
					}
				});

				if (result) {
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return result;
	}

	/**
	 * 向緩存中插入數據
	 * @param key
	 * @param value
	 * @param liveTime
	 */
	public void set(final byte[] key, final byte[] value, final long liveTime) {
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				redisTemplate.execute(new RedisCallback<Object>() {
					public Long doInRedis(final RedisConnection connection) throws DataAccessException {
						connection.set(key, value);
						if (liveTime > 0) {
							connection.expire(key, liveTime);
						}
						return 1L;
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public <T> void set(String key, T value, long liveTime, Class<T> type) {
		if (value == null)
			return;
		try {
			JacksonJsonRedisSerializer<T> serializer = new JacksonJsonRedisSerializer<T>(type);
			byte[] _value = serializer.serialize(value);
			this.set(key.getBytes(), _value, liveTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void set(String key, String value, long liveTime) {
		try {
			this.set(key.getBytes(), value.getBytes("UTF-8"), liveTime);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public <T> List<T> lRange(final String key, final Long begin, final Long end, final Class<T> type) {
		return redisTemplate.execute(new RedisCallback<List<T>>() {

			public List<T> doInRedis(RedisConnection connection) throws DataAccessException {
				JacksonJsonRedisSerializer<T> serializer = new JacksonJsonRedisSerializer<T>(type);
				List<T> list = new ArrayList<T>();
				for (byte[] element : connection.lRange(key.getBytes(), begin, end)) {
					T bean = serializer.deserialize(element);
					list.add(bean);
				}
				return list;
			}
		});
	}

	/**
	 * 從緩存中獲取數據
	 * @param key
	 * @return
	 */
	public String get(final String key) {
		String cacheValue = "";
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				cacheValue = redisTemplate.execute(new RedisCallback<String>() {
					public String doInRedis(RedisConnection connection) throws DataAccessException {
						try {
							byte[] cacheBytes = connection.get(key.getBytes());
							if (cacheBytes != null) {
								String cacheStr = new String(cacheBytes, "utf-8");
								return cacheStr;
							}
						} catch (Exception e) {
							LOG.info(e.getMessage());
						}
						return "";
					}
				});
				if (!StringUtils.isEmpty(cacheValue))
					break;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return cacheValue;
	}

	public <T> T get(final String key, final Class<T> clazz) {
		T t = null;
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			t = redisTemplate.execute(new RedisCallback<T>() {
				public T doInRedis(RedisConnection connection) throws DataAccessException {
					byte[] data = connection.get(key.getBytes());
					if (data != null)
						return new JacksonJsonRedisSerializer<T>(clazz).deserialize(data);
					return null;
				}
			});

			if (t != null)
				break;
		}
		return t;
	}
	
	public <T> Long rPush(final String key, final List<T> list, final Class<T> type, final long expire) {
		if (list == null) {
			return 0L;
		}
		return redisTemplate.execute(new RedisCallback<Long>() {

			public Long doInRedis(RedisConnection connection) throws DataAccessException {
				JacksonJsonRedisSerializer<T> serializer = new JacksonJsonRedisSerializer<T>(type);
				connection.multi();
				for (T value : list) {
					connection.rPush(key.getBytes(), serializer.serialize(value));
				}
				if (expire > 0) {
					connection.expire(key.getBytes(), expire);
				}
				connection.exec();
				return new Long(list.size());
			}

		});
	}

	/**
	 * 清空緩存
	 */
	public void flushDB() {
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				redisTemplate.execute(new RedisCallback<String>() {
					public String doInRedis(RedisConnection connection) throws DataAccessException {
						connection.flushDb();
						return "ok";
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 添加至有序集合
	 * @param key
	 * @param score
	 * @param value
	 */
	public void zadd(final byte[] key, final double score, final byte[] value) {
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				redisTemplate.execute(new RedisCallback<String>() {
					public String doInRedis(RedisConnection connection) throws DataAccessException {
						connection.zAdd(key, score, value);
						return "ok";
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 按條件獲取有序集合元素子集
	 * @param key
	 *            有序集合key
	 * @param min
	 *            範圍最小值
	 * @param max
	 *            範圍最大值
	 * @param offset
	 *            從第0ffset+1個元素起
	 * @param count
	 *            返回上限
	 * @return
	 */
	public Set<byte[]> zRangeByScore(final byte[] key, final double min, final double max, final long offset,
			final long count) {
		Set<byte[]> set = null;
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				set = redisTemplate.execute(new RedisCallback<Set<byte[]>>() {

					public Set<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
						return connection.zRangeByScore(key, min, max, offset, count);
					}

				});
				if (set != null) {
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return set;
	}

	/**
	 * 添加指定map至緩存
	 * @param key map唯一標識
	 * @param hashes
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void hMSet(final byte[] key, final Map<byte[], byte[]> hashes) {
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				redisTemplate.execute(new RedisCallback() {
					public Object doInRedis(RedisConnection connection) throws DataAccessException {
						connection.hMSet(key, hashes);
						return null;
					}
				});

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 獲取指定map中指定鍵對應的值列表
	 * @param key map的唯一標識
	 * @param fields 鍵數組
	 * @return 值數組
	 */
	public List<byte[]> hMGet(final byte[] key, final byte[]... fields) {
		List<byte[]> cacheValue = null;
		for (RedisTemplate<String, String> redisTemplate : redisTemplateList) {
			try {
				cacheValue = redisTemplate.execute(new RedisCallback<List<byte[]>>() {
					public List<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
						return connection.hMGet(key, fields);
					}
				});
				if (cacheValue != null) {
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return cacheValue;
	}

	// getters and setters
	public List<RedisTemplate<String, String>> getRedisTemplateList() {
		return redisTemplateList;
	}

	public void setRedisTemplateList(List<RedisTemplate<String, String>> redisTemplateList) {
		this.redisTemplateList = redisTemplateList;
	}

}

接下來就是調用了,跟普通的service的使用方法是一樣的。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章