springmvc+rest整合redis

  最近在作一個項目須要用到關係數據庫mysql和緩存redis,以及非關係型數據庫mongoDB。昨天下午到今天上午一直在搞springmvc整合redis,期間出現的錯誤一直讓人抓狂,在網上搜索的結果也沒有解決得了本身的問題,所以整理此文但願能夠幫助到和我同樣爲整合redis而抓狂的人。html

  首先,在這裏說明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包成功了。java

如下用代碼告訴你們我是怎麼作的mysql

一、redis.propertiesweb

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

二、redis-config.xmlredis

<?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>

三、applicationContext.xmlspring

<?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>

四、jdbc.propertiessql

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

五、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>

六、模塊代碼apache

Member.javaspring-mvc

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);
    }
}

七、運行結果

訪問地址: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。相信你必定能夠的,嘿嘿。。。

相關文章
相關標籤/搜索