使用spring4的cache操作redis

1.下载:
<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.0.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-keyvalue</artifactId>
        <version>1.2.0.RELEASE</version>
        <scope>test</scop>
spring4.3.6 的jar包

2.配置文件:

<beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:cache="http://www.springframework.org/schema/cache"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
       http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd
">


   <cache:annotation-driven />
    <context:property-placeholder location="classpath:config/redis.properties" />

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="50" />
        <property name="maxTotal" value="50" />
        <property name="maxWaitMillis" value="50" />
        <!--<property name="testOnBorrow" value="${redis.testOnBorrow}" />-->
    </bean>


<!-- redis 集群配 -->
<!--<bean id="redisClusterConfiguration" class=" org.springframework.data.redis.connection.RedisClusterConfiguration">-->
        <!--<property name="clusterNodes">-->
            <!--<set>-->
                <!--<value>192.168.6.24:3679</value>-->
                <!--<value>192.168.6.24:4679</value>-->
                <!--<value>192.168.6.24:5679</value>-->
            <!--</set>-->
        <!--</property>-->
    <!--</bean>-->





    <bean id="connectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="poolConfig" />
        <property name="port" value="6379" />
        <property name="hostName" value="192.168.6.24" />
        <!--<property name="password" value="${redis.pass}" />-->
        <!--<property name="database" value="1" /> 数据库索引-->
        <property name="timeout" value="6000" />
        <!--<constructor-arg name="clusterConfig" ref="redisClusterConfiguration"></constructor-arg>  集群配置-->

    </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>
    <!-- 配置缓存 -->
    <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg ref="redisTemplate" />
        <!--<property name="defaultExpiration" value="60" /> 默认缓存失效时间 60秒-->
        <property name="expires">
        <map>
            <entry key="demopo_update" value="180" /> <!--对缓存名称为demopo_update 设置时间1000秒-->
        </map>
        </property>
    </bean>

</beans>




3.service 代码:

package boce.demo.service.demo;

import boce.demo.dao.SelectDemoMapper;
import boce.demo.param.DemoVo;
import boce.demo.pojo.DemoPo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* Created by gjp on 2017/6/22.
*/

@Service("demoServiceImp")
public class DemoServiceImp implements  DemoService{

    @Resource
    private SelectDemoMapper selectDemoMapper;

    public int saveDemoPo(DemoPo demoPo) {
        return selectDemoMapper.saveDemoPo(demoPo);
    }
    //更新数据库时,清空缓存中的信息(防止不更新数据库)
    @CacheEvict(value ="DemoServiceImp.getDemoPoById",key = "'getDemoPoById_id'+#demoPo.did")
    public int updateDemoPo(DemoPo demoPo) {
        return selectDemoMapper.updateDemoPo(demoPo);
    }
    //查询数据,如果没有缓存到数据时缓存,已经缓存从数据库中查询
    @Cacheable(value = "DemoServiceImp.getDemoPoById",key = "'getDemoPoById_id'+#id")
    public DemoPo getDemoPoById(final Integer id){
        DemoPo demoPo = selectDemoMapper.getDemoPoById(id);
        return demoPo;
    }

    @Cacheable(value = "demopo_update",key = "'getDemoPoById_id'+#demoPo.did")
    public DemoPo updateDemoPoVal(DemoPo demoPo) {
        int res = selectDemoMapper.updateDemoPo(demoPo);
        if(res <=0){
            demoPo = null;
        }
        return demoPo;
    }
    //删除数据库时,删除缓存
    @CacheEvict(value ="DemoServiceImp.getDemoPoById",key = "'getDemoPoById_id'+#id")
    public int deleteById(Integer id) {
        return selectDemoMapper.deleteById(id);
    }

    public void testMethod() {

    }


}


4.测试类:

package gjp.test;

import boce.demo.pojo.DemoPo;
import boce.demo.service.demo.DemoService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

/**
* Created by gjp on 2017/7/5.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:dataSpring.xml",
        "classpath:application-service.xml","classpath:redis-config.xml"})//
public class TestUtil extends AbstractJUnit4SpringContextTests {
    @Resource
    private DemoService demoServiceImp;

    @Test
    public void isUserTest() {
        int id = 61;
            DemoPo po = demoServiceImp.getDemoPoById(id);
            if (null != po) {
                System.out.println(po + "-----------第一次查询");
            }

            DemoPo po1 = demoServiceImp.getDemoPoById(id);
            if (null != po1) {
                System.out.println(po1 + "=============第二次信息");
            }

    }

    @Test
    public void delbyId(){
        int id =73;
        int i =demoServiceImp.deleteById(id);
        System.out.println(i);
    }


    @Test
    public void saveObj(){
        for(int i=0;i<3;i++) {
            DemoPo demoPo = new DemoPo();
            demoPo.setUnitcost("50"+i);
            demoPo.setAttr1("60"+i);
            demoPo.setPstatus("1");
            demoPo.setProductid("1234567"+i);
            demoPo.setListprice("30");
            int res = demoServiceImp.saveDemoPo(demoPo);
            System.out.println(res);
        }
    }


    @Test
    public void updateObj(){
        //int i=9;
        for(int i=0;i<4;i++) {
            DemoPo demoPo = new DemoPo();
            demoPo.setUnitcost("300"+i);
            demoPo.setAttr1("3000"+i);
            demoPo.setPstatus("1");
            demoPo.setProductid("365"+i);
            demoPo.setListprice("330");
            demoPo.setDid(61);
            int res = demoServiceImp.updateDemoPo(demoPo);
            System.out.println(res +"更新次数"+i);
        }
    }


    @Test
    public void updateObjVal(){
        //int i=9;
         for(int i=0;i<3;i++) {
        DemoPo demoPo = new DemoPo();
        demoPo.setUnitcost("100"+i);
        demoPo.setAttr1("100"+i);
        demoPo.setPstatus("1");
        demoPo.setProductid("199"+i);
        demoPo.setListprice("30");
        demoPo.setDid(70);
        DemoPo poVal = demoServiceImp.updateDemoPoVal(demoPo);
        System.out.println(poVal +"更新次数"+i);
         }
    }

}


查询日志:

2017-07-19 11:06:43 DEBUG 150 [org.mybatis.spring.SqlSessionUtils] SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1e45f13] was not registered for synchronization because synchronization is not active
2017-07-19 11:06:43 DEBUG 87 [org.mybatis.spring.transaction.SpringManagedTransaction] JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@a809c0] will not be managed by Spring
2017-07-19 11:06:43 DEBUG 139 [boce.demo.dao.SelectDemoMapper.getDemoPoById] ==>  Preparing: select * from demopo p where p.did=?
2017-07-19 11:06:43 DEBUG 139 [boce.demo.dao.SelectDemoMapper.getDemoPoById] ==> Parameters: 61(Integer)
2017-07-19 11:06:43 DEBUG 139 [boce.demo.dao.SelectDemoMapper.getDemoPoById] <==      Total: 1
2017-07-19 11:06:43 DEBUG 123 [com.alibaba.druid.pool.PreparedStatementPool] {conn-10001, pstmt-20000} enter cache
2017-07-19 11:06:43 DEBUG 193 [org.mybatis.spring.SqlSessionUtils] Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1e45f13]
boce.demo.pojo.DemoPo@98daa5-----------第一次查询
boce.demo.pojo.DemoPo@12d0e04=============第二次信息

从日志可以看出:第一次数据从数据库中得到,第二次数据从redis 缓存中获得。


猜你喜欢

转载自gjp014.iteye.com/blog/2384984