springmvc整合redis架构搭建实例

抽空之余看了一下redis,所以整理了一下Springmvc整合redis,springmvc的环境搭建、redis的安装这个我就不写了,直接从整合开始


项目结构


pom.xml

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ssm</groupId>
    <artifactId>springmvc-master</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>springmvc-master Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <build>
        <finalName>springmvc-master</finalName>
        <plugins>
            <!--mybatis 逆向工程插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <properties>
        <spring.version>4.2.3.RELEASE</spring.version>
    </properties>
    <dependencies>
        <!-- springframe start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- springframe end -->

        <!--aspectj start-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.6</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.6</version>
        </dependency>
        <!--aspectj end-->

        <!--c3p0-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.1</version>
        </dependency>

        <!--servlet/jsp api start-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <!--servlet/jsp api end-->

        <!--junit4-->
        <!--<dependency>-->
            <!--<groupId>junit</groupId>-->
            <!--<artifactId>junit</artifactId>-->
            <!--<version>4.11</version>-->
            <!--<scope>test</scope>-->
        <!--</dependency>-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!--mybatis spring整合-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- 物理分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>

        <!--mysql driver-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <!--jstl 标签库-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 文件上传所需依赖 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.41</version>
        </dependency>
        <!-- log4j日志包 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.6</version>
        </dependency>
        <!-- config redis data and client jar -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.1.RELEASE</version>
        </dependency>
        <!-- 分布式session共享 -->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>1.2.1.RELEASE</version>
        </dependency>
    </dependencies>

</project>


applicationContext-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"
       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">

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.ssm.redis"/>

    <!--获取配置文件-->
    <context:property-placeholder location="classpath:config/database.properties" ignore-unresolvable="true"/>

    <!-- jedis 配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!-- 控制一个pool最多有多少个状态为idle(空闲)的jedis实例 -->
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="minIdle" value="${redis.minIdle}" />
        <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"  destroy-method="destroy" depends-on="poolConfig">
        <property name="poolConfig" ref="poolConfig"/>
        <!-- redis端口 -->
        <property name="port" value="${redis.port}"/>
        <!-- redis主机地址 -->
        <property name="hostName" value="${redis.host}"/>
        <property name="timeout" value="${redis.timeout}"/>
    </bean>

    <!-- redis操作模板,面向对象的模板 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
         <!--如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误-->
        <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>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:config/spring/applicationContext-*.xml</param-value>
    </context-param>
    <!--配置spring listener-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置log4j-->
    <context-param>
        <param-name>log4jConfigListener</param-name>
        <param-value>classpath*:config/log4j.properties</param-value>
    </context-param>
    <!--log4jRefreshInterval为100000表示 开一条watchdog线程每10秒扫描一下配置文件的变化;   -->
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>100000</param-value>
    </context-param>
    <!-- 使用监听加载log4j的配置文件 -->
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <!--解决POST乱码-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--springmvc前端控制器配置-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:config/spring/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>


database.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/temp?characterEncoding=UTF-8
jdbc.username = root
jdbc.password = root

# redis 基础配置
redis.host=localhost
redis.port=6379
redis.timeout=-1
redis.maxIdle=100
redis.minIdle=8
redis.maxWait=-1
#//在获取连接的时候检查有效性, 默认false
redis.testOnBorrow=true



封装一个操作hash基本数据类型的工具类 RedisCacheUtil.java


package com.ssm.redis;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by xxx on 2018
 * Description:
 * User: datah
 */
@Component("redisCache")
public class RedisCacheUtil {

    @Resource
    private StringRedisTemplate redisTemplate;

    /*
     * redis 支持五种基本类型
     * string、hash、list、set、sorted set
     *
     */

    /**
     * 添加String的值
     *
     * @param k
     * @param v
     * @Description
     */
    public void set(String k, String v) {
        if (isEmpty(k)) {
            return;
        }
        redisTemplate.opsForValue().set(k, v);
    }

    /**
     * 获取String的值
     *
     * @param k
     * @Description
     */
    public String get(String k) {
        if (isEmpty(k)) {
            return null;
        }
        return redisTemplate.opsForValue().get(k);
    }

    public void del(String k) {
        if (isEmpty(k)) {
            return;
        }
        redisTemplate.opsForValue().get(k);
    }

    /**
     * 向Hash中添加值
     *
     * @param key   可以对应数据库中的表名
     * @param field 可以对应数据库表中的唯一索引
     * @param value 存入redis中的值
     */
    public void hset(String key, String field, String value) {
        if (key == null || "".equals(key)) {
            return;
        }
        redisTemplate.opsForHash().put(key, field, value);
    }

    /**
     * 从redis中取出值
     *
     * @param key
     * @param field
     * @return
     */
    public String hget(String key, String field) {
        if (key == null || "".equals(key)) {
            return null;
        }
        return (String) redisTemplate.opsForHash().get(key, field);
    }

    /**
     * 判断 是否存在 key 以及 hash key
     *
     * @param key
     * @param field
     * @return
     */
    public boolean hexists(String key, String field) {
        if (key == null || "".equals(key)) {
            return false;
        }
        return redisTemplate.opsForHash().hasKey(key, field);
    }

    /**
     * 查询 key中对应多少条数据
     *
     * @param key
     * @return
     */
    public long hsize(String key) {
        if (key == null || "".equals(key)) {
            return 0L;
        }
        return redisTemplate.opsForHash().size(key);
    }

    /**
     * 删除
     *
     * @param key
     * @param field
     */
    public void hdel(String key, String field) {
        if (key == null || "".equals(key)) {
            return;
        }
        redisTemplate.opsForHash().delete(key, field);
    }

    /**
     * @Description 判断key是否为null
     * @Return
     */
    public Boolean isEmpty(String key) {
        if (key == null || "".equals(key)) {
            return true;
        }
        return false;
    }
}

编写测试类

package com.ssm.utils;

import com.ssm.redis.RedisCacheUtil;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by xxx
 * Description:
 * User: datah
 */
public class redisTest {

    private RedisCacheUtil redisCache;
    private static  String key;
    private static  String field;
    private static  String field2;
    private static  String value;

    @Before
    public void setup(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/config/spring/applicationContext-redis.xml");
        context.start();
        redisCache = (RedisCacheUtil)context.getBean("redisCache");
    }

    static {
        key = "student1";
        field = "name";
        field2 = "address";
        value = "小赤佬";
    }

    @Test
    public void t0(){
        redisCache.hset(key,field,value);
        redisCache.hset(key,field2,"华中上海市嘉定区");
        System.out.println("数据保存成功");
    }

    @Test
    public void t1(){
        String re = redisCache.hget(key, field);
        String re2 = redisCache.hget(key, field2);
        System.out.println("得到的数据:" + re);
        System.out.println("得到的数据:" + re2);
    }
    
}


Controller

    @Resource
    private RedisCacheUtil redisCache;

    @RequestMapping(value = "/redisTest",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String redisTest(){
        String key = "student1";
        if(redisCache.hexists(key,"name")){
            String name = redisCache.hget(key,"name");
            String age = redisCache.hget(key,"address");
            return name+","+age;
        }
        return null;
    }

启动tomcat访问就可以显示了

原文地址:https://www.cnblogs.com/xbq8080/p/6739152.html


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。This article original articles for bloggers, shall not be reproduced without the permission of the blogger. https://blog.csdn.net/JavaReact/article/details/79963708
个人分类: java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭