欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot2.x redis做缓存

程序员文章站 2022-07-07 11:38:16
...

为啥写这篇文章,因为为自己记录下自己的学习过程,和遇到的坑。不断地踩坑弄了好久终于自己尝试成功。网上大部分都是1.0版本的配置,现在2.0已经不用了,相关构造函数已经不存在

1.首先搭建springboot环境就不多说了,自行看网上的资料

2.导入Redis依赖

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

        </dependency>

网上的各种依赖,反正这一个就行

3.写一个配置文件

package com.xl.controller;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.lang.reflect.Method;
import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    // 自定义key生成器
    @Bean
    public KeyGenerator keyGenerator(){
        return (o, method, params) ->{
            StringBuilder sb = new StringBuilder();
            sb.append(o.getClass().getName()); // 类目
            sb.append(method.getName()); // 方法名
            for(Object param: params){
                sb.append(param.toString()); // 参数名
            }
            return sb.toString();
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(60)) //设置有效时间
                // 设置key的序列化方式
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                // 设置value的序列化方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
                // 不缓存null值
                .disableCachingNullValues();
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }

    // key键序列化方式
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }

    // value值序列化方式
    private GenericJackson2JsonRedisSerializer valueSerializer(){
        return new GenericJackson2JsonRedisSerializer();
    }

}

如果redisConnectionFactory 这个会报错的话可以不用管他一样可以正常运行,应该是编译器的问题
下面是一些测试类

1.mapper

package com.xl.controller;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

@Repository
public interface RedisCacheTestMapper {
    @Select("select garden_id from garden where garden_name=#{id}")
    Integer   setRedisCache(@Param("id") String  id);
}

2.service

package com.xl.service;


import com.xl.controller.RedisCacheTestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "garden")
public class RedisCacheTest {

    @Autowired
    RedisCacheTestMapper redisCacheTestMapper;
    @Cacheable(value = "user")
    public Integer  redisCacheget(String  id){

       return redisCacheTestMapper.setRedisCache(id);
    }
}

3.controller

    @ApiOperation( "hellod")
    @RequestMapping(value = "/webb",method = RequestMethod.POST)
    @ApiImplicitParam(name = "pwd",value = "1223ghhjh",dataType = "String" ,paramType = "query")
    public Integer  hello(@RequestBody String  id ){
       Integer dd = redisCacheTest.redisCacheget(id);
      log.info("redis+++++++++++++++++++++++++++"+estService.getRedis("user::com.xl.service.RedisCacheTestredisCacheget廖彩禄的果园"));
        return redisCacheTest.redisCacheget(id);
    }

相关标签: springboot