springboot中cache的使用 redis篇

1.项目目录

springboot中cache的使用 redis篇

2.application.yml

spring:
  application:
    name: cache
  redis:
    host: 47.97.219.159         #redis的IP地址
    port: 6379                  #redis的端口号
    timeout: 20000
    password: lykj
    pool:
        max-active: 500     #控制一个 pool 可分配多少个jedis实例
        min-idle: 5         #控制一个 pool 最少有多少个状态为 idle 的redis实例
        max-idle: 10        #控制一个 pool 最多有多少个状态为 idle 的redis实例
        max-wait: -1        #当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException

server:
  port: 8021

3.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">
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.5.RELEASE</version>
    </parent>


<modelVersion>4.0.0</modelVersion>
    <artifactId>spring-boot-cache</artifactId>
    <packaging>jar</packaging>

    <dependencies>

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

        <!-- redis引入 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>

    </dependencies>
    
</project>
4.RedisConfig

package com.codebase.springboot.cache;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @describe:
 * @author:houkai
 * @Date: 2018/4/4 15:00
 */
@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}
5.User

package com.codebase.springboot.cache.entity;
import java.io.Serializable;
/**
 * @describe:
 * @author:houkai
 * @Date: 2018/4/4 14:57
 */
public class User implements Serializable{

    private static final long serialVersionUID = 1706345647537291615L;

    private String userId;

    private String userName;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

6.TestController
package com.codebase.springboot.cache.controller;

import com.codebase.springboot.cache.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @describe:
 * @author:houkai
 * @Date: 2018/4/4 14:56
 */
@RestController
public class TestController {

    private Logger log = LoggerFactory.getLogger(TestController.class);

    /**
     *方法被调用且更新缓存
     * @CachePut 应用到写数据的方法上,如新增/修改方法,调用方法时会自动把相应的数据放入缓存
     *    condition : 如果条件满足则使用缓存,否则不使用缓存
     *    result.userId 的意思是User对象中的getUserId() 方法返回的结果
     * @return
     */
    @PostMapping("insert")
    @CachePut(value = "user", condition = "#result != null", key = "#result.userId")
    public User insert(){
        User user = new User();
        user.setUserId("000000");
        user.setUserName("name");
        return user;
    }

    /**
     * @Cacheable 应用到读取数据的方法上,先从缓存中读取,如果没有再从DB获取数据,然后把数据添加到缓存中
     *      unless 表示条件表达式成立的话不放入缓存
     * @param userId
     * @return
     */
    @PostMapping("query")
    @Cacheable(value = "user", key = "#userId", unless = "#result eq null")
    public User query(@RequestBody int userId){
        log.info("=========方法执行====");
        User user = new User();
        user.setUserId("01111");
        user.setUserName("name");
        return user;
    }

    /**
     * @CacheEvict 用到删除数据的方法上,调用方法时会从缓存中删除对应key的数据
     * @param userId
     */
    @PostMapping("delete")
    @CacheEvict(value = "user", key = "#userId")
    public void delete(@RequestBody int userId){
        log.info("=========方法执行====");
    }

}