Springboot 使用Redis注解

本文介绍如何在Spring Boot项目中整合Redis缓存,并通过具体示例演示如何使用注解方式配置Redis缓存,包括配置文件设置、RedisConfiguration类定义及业务层注解使用等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Springboot 使用Redis注解

配置yml

spring:
  cache:
    cache-names: mdc-cache
  redis:
    host: ${spring.redis.host}
    password: ${spring.redis.password}
    port: ${spring.redis.port}
    timeout: ${spring.redis.timeout}

RedisConfiguration配置

package com.paascloud.provider.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.RedisCacheManager;
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.Jackson2JsonRedisSerializer;

/**
 * The class Redis configuration.
 * Created by paascloud.net@gmail.com
 */
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {

    /**
     * Key generator key generator.
     *
     * @return the key generator
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };

    }

    /**
     * Cache manager cache manager.
     *
     * @param redisTemplate the redis template
     *
     * @return the cache manager
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }

    /**
     * Redis template redis template.
     *
     * @param factory the factory
     *
     * @return the redis template
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

web层

    @PostMapping(value = "/get4City")
    @ApiOperation(httpMethod = "POST", value = "查看四级地址")
    public Wrapper<List<TreeNode>> get4City() {
        logger.info("get4City - 获取四级地址");
        List<TreeNode> treeNodeList = mdcAddressService.get4City();
        return WrapMapper.ok(treeNodeList);
    }

serviceImpl

@Override
    @Cacheable(cacheNames="mdc-cache")
    public List<TreeNode> get4City() {
        List<MdcAddress> mdcAddresses = mdcAddressMapper.selectAll();
        List<TreeNode> treeNodeList = buildGroupTree(mdcAddresses);
        logger.info("treeNodeList={}", treeNodeList);
        return treeNodeList;
    }

小坑

java.lang.ClassCastException: org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.String

解决办法

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport  {
  @Bean
  @Override
  public KeyGenerator keyGenerator() { ... }

  ...
}

参考
http://blog.csdn.net/a67474506/article/details/52608855

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值