您的位置:首页 > 数据库 > Redis

J2ee项目从0搭建(十一):在项目中集成Redis,用于数据的存储或者缓存

2016-08-07 22:17 507 查看

一、Redis安装

已经安装好redis的可以直接进入下一步,没有的可以先进行安装:Linux(CentOS
7)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上

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redis 缓存
相关文章推荐