天天看点

在SpringMVC中添加redis并实现简单的增删改查

1.首先在pom文件中引入jar包,注意jar包之间的冲突:

   <!-- redis -->

         <!-- config redis data and client jar-->

        <dependency>  

            <groupId>org.springframework.data</groupId>  

            <artifactId>spring-data-redis</artifactId>  

            <version>1.3.4.RELEASE</version>  

        </dependency>      

        <dependency>

           <groupId>redis.clients</groupId>

           <artifactId>jedis</artifactId>

           <version>2.4.1</version>

        </dependency>

2.在application.xml在添加redis配置文件的引用:

<?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:p="http://www.springframework.org/schema/p"

        xmlns:aop="http://www.springframework.org/schema/aop"

        xmlns:tx="http://www.springframework.org/schema/tx"

        xmlns:util="http://www.springframework.org/schema/util"

        xsi:schemaLocation="http://www.springframework.org/schema/beans 

           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

           http://www.springframework.org/schema/aop 

           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd

           http://www.springframework.org/schema/tx 

           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

           http://www.springframework.org/schema/util 

           http://www.springframework.org/schema/util/spring-util-4.0.xsd

           http://www.springframework.org/schema/context     

           http://www.springframework.org/schema/context/spring-context-4.0.xsd"

           >

    <context:component-scan base-package="com.qfeng"></context:component-scan>

    <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>

    <util:properties id="appConfig" location="classpath:jdbc.properties"/>

    <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}"/>

        <property name="maxActive" value="${jdbc.maxActive}"/>

        <property name="maxIdle" value="${jdbc.maxIdle}"/>

        <property name="maxWait" value="${jdbc.maxWait}"/>

        <property name="initialSize" value="${jdbc.initialSize}"/>

        <property name="minIdle" value="${jdbc.minIdle}"/>

        <property name="validationQuery" value="${jdbc.validation.query}"/>

    </bean> 

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <!-- 注入数据库连接池 -->

        <property name="dataSource" ref="dataSource"/>

        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->

        <property name="configLocation" value="classpath:config/mybatis-config.xml"/>

        <!--&lt;!&ndash; 扫描entity包 使用别名 &ndash;&gt;-->

        <!--<property name="typeAliasesPackage" value="com.moy..test.entity"/>-->

        <!-- 扫描sql配置文件:mapper需要的xml文件 -->

        <!-- <property name="mapperLocations" value="classpath:com/qfeng/healthydao/*-mapper.xml"/> -->

    </bean>

    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">     

          <property name="dataSource" ref="dataSource"></property>

    </bean>

       <!--把事务控制在Service层-->

    <aop:config>    

        <aop:pointcut id="pc" expression="execution(* com.qfeng.service.*.*(..))" /> <!--把事务控制在Service层-->

      </aop:config>

      <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <!-- 注入sqlSessionFactory -->

       <!--  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> -->

        <!-- 给出需要扫描Dao接口包 -->

        <property name="basePackage" value="com.qfeng.dao"/>

    </bean>

    <!-- 引入同文件夹下的redis属性配置文件 -->

    <import resource="redis-context.xml"/>

</beans>

3.配置redis-context.xml文件:

<beans    xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:p="http://www.springframework.org/schema/p"

       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.0.xsd

      http://www.springframework.org/schema/tx

      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

      http://www.springframework.org/schema/context

      http://www.springframework.org/schema/context/spring-context-3.0.xsd

         ">

  <!-- scanner redis properties  -->

  <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/>

  <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> 

    <property name="maxIdle" value="${redis.maxIdle}" /> 

    <property name="maxTotal" value="${redis.maxTotal}" /> 

    <property name="MaxWaitMillis" value="${redis.MaxWaitMillis}" /> 

    <property name="testOnBorrow" value="${redis.testOnBorrow}" /> 

  </bean> 

  <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 

    p:host-name="${redis.host}"

    p:port="${redis.port}"

    p:password="${redis.pass}" 

    p:pool-config-ref="poolConfig"/> 

   <!-- 配置RedisTemplate -->

    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />

    <bean id="cacheRedisTemplate" class="org.springframework.data.redis.core.RedisTemplate" autowire="byType">

        <property name="connectionFactory" ref="connectionFactory" />

        <property name="keySerializer" ref="stringRedisSerializer" />

        <property name="hashKeySerializer" ref="stringRedisSerializer" />

        <property name="valueSerializer" ref="stringRedisSerializer" />

        <property name="hashValueSerializer" ref="stringRedisSerializer" />

    </bean>

</beans> 

4.配置redis.properties

# Redis settings

#redis.host=192.168.20.101

#redis.port=6380

#redis.pass=foobared

redis.host=127.0.0.1

redis.port=6379

redis.pass=

redis.maxIdle=300

redis.maxTotal=600

redis.MaxWaitMillis=1000

redis.testOnBorrow=true

5.编写controller:

package com.qfeng.controller;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

@Controller

@RequestMapping("/redis/")

public class RedisDemoController {

    @Autowired

    private RedisTemplate<String, Object>  redisTemplate;

    public static final String SUCCESS = "success";

    public static final String FAIL = "fail";

    @ResponseBody

    @RequestMapping("/insert")

    public String insert(String key,String value){

        try{

            System.out.println(key+"---------------"+value);

            redisTemplate.opsForValue().set(key, value,60*10,TimeUnit.SECONDS);

            return SUCCESS;

        }catch(Exception e){

            e.printStackTrace();

            return e.getMessage();

        }

    }

    @ResponseBody

    @RequestMapping("/find")

    public String find(String key){

        try{

            String value = (String) redisTemplate.opsForValue().get(key);

            System.out.println(key+":"+value);

            return value;

        }catch(Exception e){

            e.printStackTrace();

            return e.getMessage();

        }

    }

    @ResponseBody

    @RequestMapping("/delete")

    public String delete(String key){

        try{

            redisTemplate.delete(key);

            return SUCCESS;

        }catch(Exception e){

            e.printStackTrace();

            return e.getMessage();

        }

    }

    @ResponseBody

    @RequestMapping("/update")

    public String update(String key,String value){

        try{

            if(find(key) != null){

                redisTemplate.opsForValue().set(key, value,60*10,TimeUnit.SECONDS);

                return SUCCESS;

            }

            else

                return FAIL;

        }catch(Exception e){

            e.printStackTrace();

            return e.getMessage();

        }

    }

}

6.启动项目,进行增删改查测试。

ps:配置文件的目录结构:

在SpringMVC中添加redis并实现简单的增删改查

参考博客地址:https://blog.csdn.net/qq_39429962/article/details/84843737