最近在做一个项目需要用到关系数据库mysql和缓存redis,以及非关系型数据库mongoDB。昨天下午到今天上午一直在搞springmvc整合redis,期间出现的错误一直让人抓狂,在网上搜索的结果也没有解决得了自己的问题,因此整理此文希望可以帮助到和我一样为整合redis而抓狂的人。

  首先,在这里说明springmvc整合redis所需要的jar包,commons-pool-1.6.jar、commons-pool2-2.4.2.jar、jedis-2.9.0.jar、spring-data-commons-1.8.6.RELEASE.jar、spring-data-redis-1.8.6.RELEASE.jar。这里主要用到了这些jar包,期间遇到的jar包冲突问题也是醉醉的了,一直在倒腾jar包,最后终于使用以上几个jar包成功了。

以下用代码告诉大家我是怎么做的

1、redis.properties

redis.ip=127.0.0.1
redis.port=6379
redis.pool.maxActive=100
redis.pool.maxIdle=300
redis.pool.maxWait=1000
redis.pool.testOnBorrow=true

2、redis-config.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:aop="http://www.springframework.org/schema/aop"
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.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-autowire="byName" default-lazy-init="true"> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="maxTotal" value="${redis.pool.maxActive}" />
<property name="maxWaitMillis" value="${redis.pool.maxWait}" />
<property name="testOnBorrow" value="${redis.pool.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.ip}" />
</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.JdkSerializationRedisSerializer" />
</property>
</bean>
</beans>

3、applicationContext.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" xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"
default-autowire="byName"> <!-- 启动annotation支持 -->
<context:annotation-config />
<context:component-scan base-package="com.fp.daoImpl,com.fp.serviceImpl,com.fp.rest"></context:component-scan>
<mvc:annotation-driven/>
<!-- <util:properties id="jdbcProps" location="classpath:jdbc.properties"></util:properties> --> <context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties" /> <!-- 导入redis的配置文件 -->
<import resource="redis-config.xml"/> <!-- 配置mysql数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置jdbctemplate,并为其注入dataSource数据源 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> </beans>

4、jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf8
jdbc.username = root
jdbc.password =root

5、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>JerseyProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>  <!-- 使用rest风格-->
<servlet>
<servlet-name>restService</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.fp.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>restService</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

6、模块代码

Member.java

package com.fp.entity;

import javax.xml.bind.annotation.XmlRootElement;

import com.ems.base.BaseModel;

@XmlRootElement
public class Member extends BaseModel{ private static final long serialVersionUID = -1959528436584592183L;
private String id;
private String nickname; public Member(){} public Member(String id, String nickname){
this.setId(id);
this.setNickname(nickname);
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getNickname() {
return nickname;
} public void setNickname(String nickname) {
this.nickname = nickname;
} }

MemberDao

package com.fp.dao;

import com.fp.entity.Member;

public interface MemberDao {

    Member get(String keyId);

}

MemberDaoImpl

package com.fp.daoImpl;

import java.io.Serializable;

import javax.annotation.Resource;

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.RedisSerializer;
import org.springframework.stereotype.Repository; import com.fp.dao.MemberDao;
import com.fp.entity.Member; @Repository(value = "memberDao")
public class MemberDaoImpl implements MemberDao { @Autowired
private RedisTemplate<Serializable, Object> redisTemplate; @Resource
public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
} /**
* 读取缓存
*
* @param key
* @return
*/
public Member get(final String keyId) {
Member result = redisTemplate.execute(new RedisCallback<Member>() {
public Member doInRedis(RedisConnection connection)
throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
byte[] key = serializer.serialize(keyId);
byte[] value = connection.get(key);
if (value == null) {
return null;
}
String nickname = serializer.deserialize(value);
System.out.println("nickname::"+nickname);
return new Member(keyId, nickname);
}
});
return result;
}
}

MemberService

package com.fp.service;

import com.fp.entity.Member;

public interface MemberService {

    public Member get(String id);
}

MemberServiceImpl

package com.fp.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.fp.dao.MemberDao;
import com.fp.entity.Member;
import com.fp.service.MemberService; @Service("memberService")
public class MemberServiceImpl implements MemberService { @Autowired
private MemberDao memberDao; public Member get(String id) {
return memberDao.get(id);
}
}

MemberResource(提供rest服务)

package com.fp.rest;

import com.fp.entity.Member;
import com.fp.service.MemberService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController; @RestController
@Path("/member")
public class MemberResource { @Autowired
private MemberService memberService; @Path("/{id}")
@GET //表示此服务路径基于get请求模式
@Produces(MediaType.APPLICATION_JSON+";charset=utf-8") //表示响应的结果以文本方式返回
public Member get(@PathParam("id") String id){
return memberService.get(id);
}
}

7、运行结果

访问地址:http://localhost:8080/JerseyProject/member/id,运行结果如下:

到此springmvc+rest+redis就整合完毕了,重要的事情再强调一遍,一定要导入版本相符的jar包,commons-pool-1.6.jar、commons-pool2-2.4.2.jar、jedis-2.9.0.jar、spring-data-commons-1.8.6.RELEASE.jar、spring-data-redis-1.8.6.RELEASE.jar。相信你一定可以的,嘿嘿。。。

springmvc+rest整合redis的更多相关文章

  1. Spring+SpringMVC+Mybatis整合redis

    SSM整合redis redis是一种非关系型数据库,与mongoDB不同的是redis是内存数据库,所以访问速度很快.常用作缓存和发布-订阅式的消息队列. 这里用的是ssm框架+maven构建的项目 ...

  2. springmvc整合redis架构搭建实例

    新换环境,又有新东西可以学习了,哈皮! 抽空学习之余看了一下redis,个人对Springmvc的爱是忠贞不渝,所以整理了一下Springmvc整合redis的环境搭建.分享学习. 第一步: 创建ma ...

  3. Spring+Mybatis基于注解整合Redis

    基于这段时间折腾redis遇到了各种问题,想着整理一下.本文主要介绍基于Spring+Mybatis以注解的形式整合Redis.废话少说,进入正题. 首先准备Redis,我下的是Windows版,下载 ...

  4. SSM之整合Redis

    Redis安装与使用 第一步当然是安装Redis,这里以Windows上的安装为例. 首先下载Redis,可以选择msi或zip包安装方式 zip方式需打开cmd窗口,在解压后的目录下运行redis- ...

  5. Spring整合Redis&JSON序列化&Spring/Web项目部署相关

    几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...

  6. ssm 整合 redis(简单教程)

    最后我建议大家使用 Spring StringRedisTemplate 配置,参阅: http://blog.csdn.net/hanjun0612/article/details/78131333 ...

  7. sping整合redis,以及做mybatis的第三方缓存

    一.spring整合redis Redis作为一个时下非常流行的NOSQL语言,不学一下有点过意不去. 背景:学习Redis用到的框架是maven+spring+mybatis(框架如何搭建这边就不叙 ...

  8. [手把手教程][JavaWeb]优雅的SpringMvc+Mybatis整合之路

    来源于:http://www.jianshu.com/p/5124eef40bf0 [手把手教程][JavaWeb]优雅的SpringMvc+Mybatis整合之路 手把手教你整合最优雅SSM框架:S ...

  9. Spring4+SpringMVC+MyBatis整合思路(山东数漫江湖)

    1.Spring框架的搭建 这个很简单,只需要web容器中注册org.springframework.web.context.ContextLoaderListener,并指定spring加载配置文件 ...

随机推荐

  1. 日志输出:控制台和log文件输出日志

    self_log.py 中 import os import logging import time # 如果日志文件夹不存在,则创建 log_dir = "log" # 日志存放 ...

  2. idea配置scala和spark

    1 下载idea  路径https://www.jetbrains.com/idea/download/#section=windows 2安装spark  spark-2.1.0-bin-hadoo ...

  3. SQL Server WITH ROLLUP、WITH CUBE、GROUPING语句的应用

    CUBE:CUBE 生成的结果集显示了所选列中值的所有组合的聚合. ROLLUP:ROLLUP 生成的结果集显示了所选列中值的某一层次结构的聚合. GROUPING:当行由 CUBE 或 ROLLUP ...

  4. JDK环境变量配置目录jre,jvm

    类路径 :CLASSPATH= .;%JAVA_HOME%/lib/dt.jar;%JAVA_HOME%/lib/tools.jar   JDK的路径:JAVA_HOME = C:/Program F ...

  5. git---小乌龟提交

    下载地址:https://tortoisegit.org/ 比如我修改了文件: 1.本地提交在项目目录内右键,点击git commit按钮 2.拉去线上最新代码,与本地代码合并 3.向线上推送

  6. 如何获取iClap的内测资格

    iClap,一款拥有智能产品管理能力的系统,第一次遇见是在8月下旬的创新中国的展会上,茫茫人海中只因多看了你一眼,便深深的留在脑海里挥之不去,展会结束的当天就忍不住想要更多的了解你,登陆iClap官网 ...

  7. app安全研究

    国内Android App在线漏洞检测平台  腾讯金刚审计系统 http://service.security.tencent.com/kingkong 免费 无限制 腾讯御安全 http://yaq ...

  8. PHP中的错误信息

    PHP中的错误信息   php.ini中配置错误消息 在PHP4中,没有异常 Exception这个概念,只有 错误Error.我们可以通过修改php.ini 文件来配置用户端输出的错误信息. 在ph ...

  9. Web安全学习笔记之Nmap脚本使用指南

    nmap是一个网络连接端扫描软件,用来扫描网上电脑开放的网络连接端.确定哪些服务运行在哪些连接端,并且推断计算机运行哪个操作系统.它是网络管理员必用的软件之一,以及用以评估网络系统安全. —— 来自百 ...

  10. CentOS的Qt3和Qt4问题

    在有的系统中,装有Qt3和Qt4, 在使用qmake生成Makefile后,直接make, 出错,说没有头文件, 如果调用了qt3的qmake,那么上头的INCPATH里的头文件路径也指向了Qt3, ...