SpringBoot & SpringCache & Redis 整合

SpringBoot & SpringCache & Redis 整合

单体项目,缓存技术

步骤

1.导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.demo</groupId>
    <artifactId>SpringCacheRedisDemo</artifactId>
    <version>1.0-SNAPSHOT</version>



    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--缓存接口-->

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--缓存管理器用来序列化和反序列化的-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.编写redisCache配置类

@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
@EnableCaching
public class RedisConfig {

    /**
     * 默认情况下的模板只能支持RedisTemplate<String, String>,也就是只能存入字符串,因此支持序列化
     */
    @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer ());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer ());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    /**
     * 配置使用注解的时候缓存配置,默认是序列化反序列化的形式,加上此配置则为 json 形式
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        // 配置序列化
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
    }
}

3.编写对应SpringCache注解

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    //测试数据
    private static final    HashMap<String, Product> stringProductHashMap = new HashMap<> ();

    static {
        stringProductHashMap.put (UUID.randomUUID ().toString (),new Product (000001L,"手机"));
        stringProductHashMap.put (UUID.randomUUID ().toString (),new Product (000002L,"笔记本"));
        stringProductHashMap.put (UUID.randomUUID ().toString (),new Product (000003L,"电脑"));
        stringProductHashMap.put (UUID.randomUUID ().toString (),new Product (000003L,"飞机"));
    }




    public static void main(String[] args) {
        show();
    }

    private static void show() {
        for (String s : stringProductHashMap.keySet ()) {
            System.out.println (stringProductHashMap.get (s));
        }


    }

    /**
     * 查询
     * @param id
     * @return
     */
    @Cacheable(value = "product", key = "#id")
    @Override
    public Product select(Long id) {
        System.out.println ("我被执行了");
        log.info("查询【id】= {}", id);
        return stringProductHashMap.get(id);
    }

    /**
     * 新增或者修改
     * @param product
     * @return
     */
    @CachePut(value = "product", key = "#product.id")
    @Override
    public Product saveOrUpdate(Product product) {
        System.out.println ("我被执行了");
        stringProductHashMap.put(product.getId().toString (), product);
        log.info("保存【product】= {}", product);
        return product;
    }


    /**
     * 删除
     * @param id
     */
    @CacheEvict(value = "product", key = "#id")
    @Override
    public void delete(Long id) {
        System.out.println ("我被执行了");
        stringProductHashMap.remove(id);
        log.info("删除【id】= {}", id);
    }
}

4.测试
@Slf4j
@SpringBootTest
@Rollback(value=true)
@RunWith(SpringRunner.class)
public class RedisCacheDemoTest {

    @Autowired
    ProductServiceImpl productService;


    /**
     * 清空缓存
     */
    @Test void del(){
        for (int i = 0; i < 5; i++) {
            System.out.println (i);
            productService.delete (1L);
        }
    }

    /**
     * 查询
     */
    @Test
    public void  select(){
        for (int i = 0; i < 5; i++) {
            System.out.println (i);
            productService.select (1L);
        }
    }

    /**
     * 测试 Redis 操作  新增或修改
     */
    @Test
    public void saveOrUpdate() {
        for (int i = 0; i < 5; i++) {
            System.out.println (i);
            productService.saveOrUpdate (new Product (1L,"admin" ));
        }
    }
}
5.结果
  1. 开启缓存

在这里插入图片描述

  1. 关闭缓存
    在这里插入图片描述
其他操作都相似
可以使用AOP以及自定义注解实现个性化缓存
知识点

    @Cacheable:触发缓存写入。
    @CacheEvict:触发缓存清除。
    @CachePut:更新缓存(不会影响到方法的运行)。
    @Caching:重新组合要应用于方法的多个缓存操作。
    @CacheConfig:设置类级别上共享的一些常见缓存设置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值