深入学习java笔记-10.SpringBoot2.1之Redis缓存

pom.xml
        
            org.springframework.boot
            spring-boot-starter-data-redis
            2.1.4.RELEASE
        
        
            org.apache.commons
            commons-pool2
            2.6.2
        
application.yml
redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    timeout: 3000
    lettuce:
      pool:
        maxIdle: 200
        min-idle: 200
        max-active: 2000
        max-wait: 1000
RedisClient.java 字符串形式StringRedisTemplate
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisClient {

    @Autowired
    private StringRedisTemplate redisTpl;

    public boolean set(String key, String value){
        try {
            redisTpl.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public String get(String key){
        return redisTpl.opsForValue().get(key);
    }
}
RedisTestController.java
import com.ctgu.springstart.domain.JsonData;
import com.ctgu.springstart.domain.User;
import com.ctgu.springstart.util.JsonUtils;
import com.ctgu.springstart.util.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/redis")
public class RedisTestController {

    @Autowired
    private RedisClient redis;

    @GetMapping("add")
    public Object add(String key, String name){
        redis.set(key, name);
        return JsonData.builder().msg("add name").build();
    }

    @GetMapping("get")
    public Object get(String key){
        String value = redis.get(key);
        return JsonData.builder().data(value).msg("get name").build();
    }

    @GetMapping("save_user")
    public Object saveUser(){
        User user = new User(1, "ct", 20,
                "1234567","[email protected]");
        String userStr = JsonUtils.obj2String(user);
        boolean flag = redis.set("base:user:11", userStr);
        return JsonData.builder().data(flag).msg("get name").build();
    }

    @GetMapping("get_user")
    public Object getUser(){
        String userStr = redis.get("base:user:11");
        User user = JsonUtils.string2Obj(userStr, User.class);
        return JsonData.builder().data(user).msg("get name").build();
    }

}
RedisConfig 复杂数据结构RedisTemplate
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        //使用StringRedisSerializer来序列化和反序列化redis的key值
        RedisSerializer redisSerializer = new StringRedisSerializer();
        //key
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(redisSerializer);
        //value
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;

    }

}

你可能感兴趣的:(深入学习java笔记-10.SpringBoot2.1之Redis缓存)