redis+spring+maven平台搭建

来源:互联网 发布:linux apache2.0下载 编辑:程序博客网 时间:2024/06/10 00:59

一、什么是Redis?

      redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

它有什么特点?

(1)Redis数据库完全在内存中,使用磁盘仅用于持久性。
(2)相比许多键值数据存储,Redis拥有一套较为丰富的数据类型。
(3)Redis可以将数据复制到任意数量的从服务器。

Redis 优势?
 (1)异常快速:Redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。
 (2)支持丰富的数据类型:Redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。
(3)操作都是原子性:所有Redis操作是原子的,这保证了如果两个客户端同时访问的Redis服务器将获得更新后的值。
(4)多功能实用工具:Redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(Redis原生支持发布/订阅),任何短暂的数据,应用程序,如Web应用程序会话,网页命中计数等。

Redis 缺点?

(1)单线程

(2)耗内存


二、实例

IDE: elipse
1、新建maven项目


Group Id和Article Id名字随便取
整个项目结构:
2、配置pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.wb</groupId>  <artifactId>redis</artifactId>  <version>0.0.1-SNAPSHOT</version>    <dependencies>   <!--Redis start -->  <dependency>      <groupId>org.springframework.data</groupId>      <artifactId>spring-data-redis</artifactId>      <version>1.6.1.RELEASE</version>  </dependency>  <dependency>      <groupId>redis.clients</groupId>      <artifactId>jedis</artifactId>      <version>2.7.3</version>  </dependency>     <!--Redis end -->        <!-- https://mvnrepository.com/artifact/log4j/log4j --><dependency>    <groupId>log4j</groupId>    <artifactId>log4j</artifactId>    <version>1.2.17</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope><version>4.12</version></dependency> <dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.1.5.RELEASE</version></dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --><dependency>    <groupId>commons-logging</groupId>    <artifactId>commons-logging</artifactId>    <version>1.1.1</version></dependency>       </dependencies></project>
注意:spring-test和junit版本必须互相兼容(两个jar有些版本不互相支持)

3、 RedisUtil文件
package com.wb.redis.common;import java.io.Serializable;import java.util.Set;import java.util.concurrent.TimeUnit;import org.apache.log4j.Logger;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;/** * redis cache 工具类 *  */public final class RedisUtil {private Logger logger = Logger.getLogger(RedisUtil.class);private RedisTemplate<Serializable, Object> redisTemplate;/** * 批量删除对应的value *  * @param keys */public void remove(final String... keys) {for (String key : keys) {remove(key);}}/** * 批量删除key *  * @param pattern */public void removePattern(final String pattern) {Set<Serializable> keys = redisTemplate.keys(pattern);if (keys.size() > 0)redisTemplate.delete(keys);}/** * 删除对应的value *  * @param key */public void remove(final String key) {if (exists(key)) {redisTemplate.delete(key);}}/** * 判断缓存中是否有对应的value *  * @param key * @return */public boolean exists(final String key) {return redisTemplate.hasKey(key);}/** * 读取缓存 *  * @param key * @return */public Object get(final String key) {Object result = null;ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();result = operations.get(key);return result;}/** * 写入缓存 *  * @param key * @param value * @return */public boolean set(final String key, Object value) {boolean result = false;try {ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();operations.set(key, value);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/** * 写入缓存 *  * @param key * @param value * @return */public boolean set(final String key, Object value, Long expireTime) {boolean result = false;try {ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();operations.set(key, value);redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);result = true;} catch (Exception e) {e.printStackTrace();}return result;}public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {this.redisTemplate = redisTemplate;}}

4、applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="      http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-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/context      http://www.springframework.org/schema/context/spring-context-3.0.xsd">       <!-- 引入properties配置文件 -->     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">      <property name="locations">          <list>             <value>classpath:properties/redis.properties</value>              <!--要是有多个配置文件,只需在这里继续添加即可 -->          </list>      </property>  </bean> <!-- jedis 配置 -->     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" >           <property name="maxIdle" value="${redis.maxIdle}" />           <property name="maxWaitMillis" value="${redis.maxWait}" />           <property name="testOnBorrow" value="${redis.testOnBorrow}" />     </bean >    <!-- redis服务器中心 -->     <bean id="connectionFactory"  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >           <property name="poolConfig" ref="poolConfig" />           <property name="port" value="${redis.port}" />           <property name="hostName" value="${redis.host}" />           <!-- <property name="password" value="${redis.password}" />   -->         <property name="timeout" value="${redis.timeout}" ></property>     </bean >     <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >           <property name="connectionFactory" ref="connectionFactory" />           <property name="keySerializer" >               <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />           </property>           <property name="valueSerializer" >            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />              <!--  <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />   -->         </property>     </bean >               <bean id="redisUtil" class="com.wb.redis.common.RedisUtil" >           <property name="redisTemplate" ref="redisTemplate" />     </bean >  </beans>
valueSerializer
valueSerializer配制成
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
在redis中,容易在value前产生乱码。

5、properties文件
redis.host=127.0.0.1redis.port=6379redis.password=redis.maxIdle=100  redis.maxActive=300  redis.maxWait=1000  redis.testOnBorrow=trueredis.timeout=100000   targetNames=xxxRecordManager,xxxSetRecordManager,xxxStatisticsIdentificationManager  methodNames=  com.service.impl.xxxRecordManager= 60  com.service.impl.xxxSetRecordManager= 60  defaultCacheExpireTime=3600    fep.local.cache.capacity =10000  

6、测试
package redis;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.wb.redis.common.RedisUtil;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:applicationContext.xml" })public class DemoTest {@Autowiredprivate RedisUtil redisUtil;@Testpublic void test01() {redisUtil.set("one", "1");redisUtil.set("two", "2");redisUtil.set("three", "3");System.out.println(redisUtil.get("one"));}@Testpublic void test02() {redisUtil.remove("name");redisUtil.remove("one", "1");redisUtil.remove("two", "2");redisUtil.remove("three", "3");}}

原创粉丝点击