springboot之mysql、mybatis、SpringCache、redis缓存

需要了解

mybatis二级缓存默认开启,需要设置二级缓存介质才可生效,二级缓存底层是管理一级缓存,
将每个本地一级缓存集合化管理

二级缓存介质

Ehcache、SpringCache、Redis

SpringCache缓存介质的不同实现

springboot之mysql、mybatis、SpringCache、redis缓存_第1张图片

代码

项目结构
springboot之mysql、mybatis、SpringCache、redis缓存_第2张图片

创建database

name :demo
table :user(id,name,age)
statement:insert into user values(1,"admin",23);

pom
多加如下依赖

    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        1.1.1
    
    
    
        mysql
        mysql-connector-java
    
    
    
    
        org.springframework.boot
        spring-boot-starter-data-redis
    

yml

server:
  servlet:
    context-path: /
  port: 8088
spring:
  application:
    name: springboot-mysql-mybatis-springcache-redis
  redis:
      #表示连接redis 0表示数据库index
      database: 0
      host: 127.0.0.1
      port: 6379
      password: root
  datasource:
    url: jdbc:mysql://localhost:3306/demo?characterEncoding=UTF-8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
  #设置SpringCache类型为redis实现
  cache:
    type: redis
#mybatis配置
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  config-location: classpath:mybatis/mybatis-config.xml
#指定某个包发生日志操作就在后台打印,不设置无法打印预编译SQL
logging:
  level:
    com:
      whotw: debug

mybatis-config.xml




    
    

userMapper.xml





    
        
        
        
    
    
                `id`,
                `name`,
                `age`
    
    
    
        INSERT INTO user(name,age) values (#{user.name},#{user.age})
    
    
    
    
    

UserMapper

@Mapper
@Repository
public interface UserMapper {
    int insert(@Param("user") User user);
    User load(@Param("id") int id);
}

UserService

public interface UserService {
    public User load(int id);

    public boolean add(User user);

}

UserServiceImpl

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
	//文章下面会讲解@Cacheable、@CacheEvict、@CachePut使用和区别
    @Cacheable(cacheNames = {CacheConfiguration.USER_CACHE}, key = "#root.methodName+#id")
    @Override
    public User load(int id) {
        return userMapper.load(id);
    }

    @Override
    public boolean add(User user) {
        int insert = userMapper.insert(user);
        if (insert > 0) {
            return true;
        }
        return false;
    }
}

UserController

@RestController
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/load")
    public User load(int id) {
        return userService.load(id);
    }

    @RequestMapping("/add")
    public boolean add() {
        User user = new User();
        user.setName("李四");
        user.setAge(23);
        return userService.add(user);
    }
}

User

@Data
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;
    private Integer age;
}

CacheConfiguration

@Configuration
public class CacheConfiguration {
    /**
     * 用户搜素缓存
     */
    public static final String USER_CACHE = "user_cache";

    @Primary
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration
                //设置缓存的默认超时时间:30 minutes
                .entryTtl(Duration.ofMinutes(30L))
                //如果是空值,不缓存
                .disableCachingNullValues()
                //设置key序列化器
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                //设置value序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()));
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration)
                .build();
    }

    /**
     * key序列化器
     */
    private RedisSerializer keySerializer() {
        return new StringRedisSerializer();
    }

    /**
     * value序列化器
     */
    private RedisSerializer valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}
 
  

StartApp

@SpringBootApplication
/** 开启SpringCache*/
@EnableCaching
@Slf4j
public class StartApp {
    public static void main(String[] args) {
        SpringApplication.run(StartApp.class, args);
    }
}

测试

先要启动redis
多次调用此接口会发现控制台只调用了一次SQL
http://localhost:8088/load?id=1
在这里插入图片描述
redis生成相应缓存数据
springboot之mysql、mybatis、SpringCache、redis缓存_第3张图片

cache与cache-ref标签


这句配置中大部分属性都有默认配置,不用配置也可使用,即直接就可使用缓存
下面讨论下 的属性

eviction回收策略

LRU,  最近最少使用的,移除最长时间不用的对象。
FIFO,先进先出,按对象进入缓存的顺序来移除他们
SOFT, 软引用,移除基于垃圾回收器状态和软引用规则的对象。
WEAK,若引用,更积极的移除基于垃圾收集器状态和若引用规则的对象

flushInterval刷新间隔

可以被设置为任意的正整数,而且它们代表一个合理的毫秒 形式的时间段。默认情况是不设置,
也就是没有刷新间隔,缓存仅仅调用语句时【增、删、改】刷新。