redis代替mybatis做缓存

将redis作为缓存

   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>1.5.8.RELEASE</version>
        </dependency>
    </dependencies>
pom

 test文件

package com.lqh.springdataredis;

import com.lqh.springdataredis.dao.AdminDao;
import com.lqh.springdataredis.entity.Admin;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@SpringBootTest(classes = SpringdataRedisApplication.class)
@RunWith(SpringRunner.class)
public class TestClazz {

    @Resource
    AdminDao adminDao;

    @Test
    public void selectAll(){
        List<Admin> admins = adminDao.queryAll(new Admin());
        for (Admin admin : admins) {
            System.out.println(admin);

        }
        System.out.println("=========================================================");
        List<Admin> admins1 = adminDao.queryAll(new Admin());
        for (Admin admin : admins1) {
            System.out.println(admin);

        }

    }
}

 配置文件

server.port=8087

logging.level.root=error
logging.level.com.lqh.springdataredis.dao=debug

#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/girls?serverTimezone=GMT%2B8 
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.lqh.springdataredis.entity
spring.redis.host=192.168.253.11
spring.redis.port=6379

 

 自定义cache

package com.lqh.springdataredis.mycache;

import com.lqh.springdataredis.entity.Admin;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


import java.util.concurrent.locks.ReadWriteLock;

public class Mycache implements Cache {
//    这个id是namespace 这个类是mybatis 调用的所以这个构造方法的参数也是mybatis传递的

    private String id;

    public Mycache(String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        System.out.println("getId: "+id);
        /**
         * id: com.lqh.springdataredis.dao.AdminDao
         */
        return id;
    }

    /**
     * 存储从数据库中查找的数据当请求到达的时候先去缓存中去找数据如果没有数据则去数据库中去找
     * 并且将查询到的数据添加到缓存中
     * 在这个方法中将从数据库中查询到的数据保存到redis中
     * 因为这个类的是由mybatis进行调用的的那么这个类就不能使用注解的方式那么如何在springboot的项目中
     * 普通类如果想要使用spring工厂管理的组件(redisTemplate)需要做一下操作
     * implements ApplicationContextAwear会将工厂作为参数传递给你重写这类里面的所有方法就会将你传入的类交由工厂管理
     * @param o
     * @param o1
     */
    @Override
    public void putObject(Object o, Object o1) {
        System.out.println("putObject : "+o);
        System.out.println("putObject :"+o1);
        /**
         * o的值:
         * putObject : 518470582:509867698:com.lqh.springdataredis.dao.AdminDao.queryAll:0:2147483647:select
         *           id, name, birthday, mesage
         *         from girls.admin:SqlSessionFactoryBean
         * o1的值:
         * putObject :[Admin{id=1, name='朱李飞', birthday=Wed Oct 16 00:00:00 CST 2019, mesage='8888'},
         *             Admin{id=8, name='33', birthday=Fri Nov 15 00:00:00 CST 2019,
         */
//        从容器中获取redisTemplate
        RedisTemplate redisTemplate = (RedisTemplate) MyApplicationContexAware.getBeanByName("redisTemplate");
//        以json作为序列化方式
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Admin.class);
        redisTemplate.setKeySerializer(jackson2JsonRedisSerializer);
//        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
//        将数据添加到redis中 key o | value o1
        redisTemplate.opsForHash().put(id,o,o1);
    }

    /**
     * 从缓存中获取数据
     * @param o
     * @return
     */
    @Override
    public Object getObject(Object o) {
        System.out.println("getObject: "+o);
        /**
         * getObject: 518470582:509867698:com.lqh.springdataredis.dao.AdminDao.queryAll:0:2147483647:select
         *           id, name, birthday, mesage
         *         from girls.admin:SqlSessionFactoryBean
         */
        RedisTemplate redisTemplate = (RedisTemplate) MyApplicationContexAware.getBeanByName("redisTemplate");
//       id 是 key o  value o
        Object o1 = redisTemplate.opsForHash().get(id, o);
        return o1;
    }

    @Override
    public Object removeObject(Object o) {
        return null;
    }
  //当进行修改操作时会清空缓存
    @Override
    public void clear() {
        RedisTemplate redisTemplate = (RedisTemplate) MyApplicationContexAware.getBeanByName("redisTemplate");
        redisTemplate.delete(id);

    }

    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return null;
    }
}

 

 ApplicationContextAwear

package com.lqh.springdataredis.mycache;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationContexAware implements ApplicationContextAware {
    /**
     * 这个类主要是获取工厂对象用于管理
     * @param applicationContext
     * @throws BeansException
     */
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static Object getBeanByClazz(Class clazz){
        Object bean = applicationContext.getBean(clazz);
        return  bean;
    }

    public static Object getBeanByName(String name){
        Object bean = applicationContext.getBean(name);
        return bean;
    }


}

 

 

 

 

 

posted @ 2019-11-27 20:30  纳兰容若♫  阅读(488)  评论(0编辑  收藏  举报