springboot2.x redis做缓存

为啥写这篇文章,因为为自己记录下自己的学习过程,和遇到的坑。不断地踩坑弄了好久终于自己尝试成功。网上大部分都是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);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值