J2ee项目从0搭建(十一):在项目中集成Redis,用于数据的存储或者缓存
2016-08-07 22:17
507 查看
一、Redis安装
已经安装好redis的可以直接进入下一步,没有的可以先进行安装:Linux(CentOS7)Redis 安装
二、pom依赖:
Jedis是redis的java版本的客户端实现<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.5.1.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.6.1</version> </dependency>
三、spring配置
在resources目录下新建一个redis.properties:#redis setting redis.hostName =192.168.240.131 redis.port=6379 redis.timeout=15000 redis.usePool=true redis.password=buildmavenweb #jedis setting jedis.maxIdle=6 jedis.minEvictableIdleTimeMillis=300000 jedis.numTestsPerEvictionRun=3 jedis.timeBetweenEvictionRunsMillis=60000
再创建一个spring-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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 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-lazy-init="true"> <context:component-scan base-package="com.spring.demo.redis" /> <!-- 引入redis配置文件 --> <context:property-placeholder location="classpath:redis.properties" /> <!-- 连接池配置 --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- 连接池中最大空闲的连接数 --> <property name="maxIdle" value="${jedis.maxIdle}"></property> <!-- 连接空闲的最小时间,达到此值后空闲连接将可能会被移除。负值(-1)表示不移除. --> <property name="minEvictableIdleTimeMillis" value="${jedis.minEvictableIdleTimeMillis}"></property> <!-- 对于“空闲链接”检测线程而言,每次检测的链接资源的个数。默认为3 --> <property name="numTestsPerEvictionRun" value="${jedis.numTestsPerEvictionRun}"></property> <!-- “空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1. --> <property name="timeBetweenEvictionRunsMillis" value="${jedis.timeBetweenEvictionRunsMillis}"></property> </bean> <!-- Spring提供的Redis连接工厂 --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <!-- 连接池配置 --> <property name="poolConfig" ref="jedisPoolConfig"></property> <!-- Redis服务主机 --> <property name="hostName" value="${redis.hostName}"></property> <!-- Redis服务端口号 --> <property name="port" value="${redis.port}"></property> <!-- 连超时设置 --> <property name="timeout" value="${redis.timeout}"></property> <!-- 是否使用连接池 --> <property name="usePool" value="${redis.usePool}"></property> <!-- Redis服务连接密码 --> <property name="password" value="${redis.password}"></property> </bean> <!-- Spring提供的访问Redis类 --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <!-- Redis连接工厂 --> <property name="connectionFactory" ref="jedisConnectionFactory"></property> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <!-- JdkSerializationRedisSerializer支持对所有实现了Serializable的类进行序列化 --> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> </bean> </beans>
PS: 下面这段内容取自:http://shift-alt-ctrl.iteye.com/blog/1887370
spring-data-redis提供了多种serializer策略,这对使用jedis的开发者而言,实在是非常便捷。sdr提供了4种内置的serializer:
JdkSerializationRedisSerializer:使用JDK的序列化手段(serializable接口,ObjectInputStrean,ObjectOutputStream),数据以字节流存储
StringRedisSerializer:字符串编码,数据以string存储
JacksonJsonRedisSerializer:json格式存储
OxmSerializer:xml格式存储
其中JdkSerializationRedisSerializer和StringRedisSerializer是最基础的序列化策略,其中“JacksonJsonRedisSerializer”与“OxmSerializer”都是基于stirng存储,因此它们是较为“高级”的序列化(最终还是使用string解析以及构建java对象)。
RedisTemplate中需要声明4种serializer,默认为“JdkSerializationRedisSerializer”:
1) keySerializer :对于普通K-V操作时,key采取的序列化策略
2) valueSerializer:value采取的序列化策略
3) hashKeySerializer: 在hash数据结构中,hash-key的序列化策略
4) hashValueSerializer:hash-value的序列化策略
无论如何,建议key/hashKey采用StringRedisSerializer。
四、web.xml中
如果配置文件是统一的格式加载的,如:classpath:/spring-*.xml,就不许做特殊加载,否则需要将spring-redis.xml单独加载进来<!-- 加载配置文件 --> <!--contextConfigLocation在 ContextLoaderListener类中的默认值是 /WEB-INF/applicationContext.xml --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:/spring-*.xml </param-value> </context-param>
五、java代码中使用
新建一个RedisUtils.class,用来专门处理redis的相关操作:package com.spring.demo.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; /** * Created by ehsy_it on 2016/8/7. */ @Component public class RedisUtils { @Autowired private RedisTemplate<String,Object> redisTemplate; /** * 得到指定key值的value * @param key */ public Object get(String key){ return redisTemplate.boundValueOps(key).get(); } /** * 保存指定key值的value * @param key * @param value */ public void set(String key, Object value){ redisTemplate.boundValueOps(key).set(value); } /** * 删除指定key的value * @param key */ public void del(String key){ redisTemplate.delete(key); } }
六、测试
新建一个RedisMain.class类,我们通过代码存储一个String类型和list类型,并从中获取出来:package com.spring.demo.redis; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.ArrayList; import java.util.List; /** * Created by ehsy_it on 2016/8/7. */ public class RedisMain { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("/spring-redis.xml"); RedisUtils redisUtils = (RedisUtils) ctx.getBean("redisUtils"); redisUtils.set("china","瓷器"); List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); redisUtils.set("list", list); System.out.println("china=" + redisUtils.get("china")); System.out.println("list[1]=" + ((List)redisUtils.get("list")).get(1)); } }
七、异常 处理
集成中遇到问题可以查看这里解决:Redis异常总结(持续收集中);或者留言我们共同讨论。八、推荐Redis学习地址:http://www.redis.net.cn/
======================================================================================================================为了便于大家学习,项目将被开源在我的github上:
项目地址:https://github.com/gubaijin/buildmavenweb
如何将项目开源道github,请看我的另一篇博文:GitHub上创建项目 并初始化本地工程提交到GitHub上
相关文章推荐
- C#下创建存储过程用于Insert或者Update数据的Demo
- J2ee项目从0搭建(五):最新Spring下载(BOM解决jar包依赖)、集成
- 使用Redis作为SpringBoot项目数据缓存
- iOS基础8:自定义MyData/自定义SQLite用于网络判断,版本判断,图片缓存处理,下载或者上传的GET或POST请求,加密手段,.数据解析
- J2EE项目系列(四)--SSM框架构建积分系统和基本商品检索系统(Spring+SpringMVC+MyBatis+Lucene+Redis+MAVEN)(2)建立商品数据库和Lucene的搭建
- 标准功能模块组件 -- “文档管理组件,网络文档管理,网络存储”,B\S版本组件可独立运行,也可集成到其他项目里,数据结构清晰思路严谨
- Redis缓存服务搭建及实现数据读写 - Eric.Chen
- Redis缓存服务搭建及实现数据读写
- Redis缓存服务搭建及实现数据读写
- J2ee项目从0搭建(七):集成Mybatis、mybatis-generator代码生成、MySQL数据库
- 标准功能模块组件 -- “文档管理组件,网络文档管理,网络存储”,B/S版本组件可独立运行,也可集成到其他项目里,数据结构清晰思路严谨
- Redis缓存服务搭建及实现数据读写
- Redis缓存服务搭建及实现数据读写--转载
- J2ee项目从0搭建(十):在项目中集成log日志收集(slf4j+log4j)
- 在eclipse 集成maven 用于新建或者导入maven项目
- 使用SpringBoot搭建小型项目,集成mybatis,redis,swagger2,并部署在外部容器中。
- 把项目中那些恶心的无处存储的大块数据都丢到FastDFS之快速搭建
- J2ee项目从0搭建(八):集成Mybatis、mybatis-generator代码生成、Oracle数据库
- J2ee项目从0搭建(六):Spring MVC集成
- Redis缓存服务搭建及实现数据读写