SpringBoot整合redis及其注解式开发

SpringBoot配置类

注解标签

@Configuration底层是含有@Component ,所以@Configuration 具有和@Component 的作用。

@Configuration可理解为用spring的时候xml里面的标签。

注:

  1. 配置类必须以类的形式提供(不能是工厂方法返回的实例),允许通过生成子类在运行时增强(cglib 动态代理)。
  2. 配置类不能是 final 类(没法动态代理)。
  3. 配置注解通常为了通过 @Bean 注解生成 Spring 容器管理的类。
  4. 配置类必须是非本地的(即不能在方法中声明,不能是 private)。
  5. 任何嵌套配置类都必须声明为static。
  6. @Bean方法不能创建进一步的配置类(也就是返回的bean如果带有@Configuration,也不会被特殊处理,只会作为普通的 bean)。

@EnableCaching

  1. @EnableCaching注解是spring framework中的注解驱动的缓存管理功能。自spring版本3.1起加入了该注解。
  2. 如果你使用了这个注解,那么你就不需要在XML文件中配置cache manager了。
  3. 当你在配置类(@Configuration)上使用@EnableCaching注解时,会触发一个post processor,这会扫描每一个spring bean,查看是否已经存在注解对应的缓存。如果找到了,就会自动创建一个代理拦截方法调用,使用缓存的bean执行处理。

@Bean

@Bean可理解为用spring的时候xml里面的标签。

注:

  1. @Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同;

  2. @Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域;

  3. 既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Repository等注解注册bean(在需要注册的类上加注解),当然需要配置@ComponentScan注解进行自动扫描。

导入redis的依赖

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

配置application.yml

spring:
  redis:
      database: 0
      host: 192.168.147.144
      port: 6379
      password: 123456
      jedis:
          pool:
              max-active: 100
              max-idle: 3
              max-wait: -1
              min-idle: 0
      timeout: 1000

创建RedisConfig

在这里插入图片描述
记得之前我们ssm集成redis需要导入导入集成的配置文件,application-redis.xml,而在这个里面我们主要做的事情有

1、配置redis连接池
2、配置redis连接工厂
3、获得java操作redis对象,jedis
所以我们在springboot里面一样要做这些事,只不过不需要配置文件了,我们通过一个配置类和注解来实现

RedisConfig类用于Redis数据缓存。
继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。

package com.liyingdong.springboot02.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.RedisCacheConfiguration;
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;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


/**
 * redis配置类
 **/
@Configuration
@EnableCaching//开启注解式缓存
//继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 生成key的策略 根据类名+方法名+所有参数的值生成唯一的一个key
     *
     * @return
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... 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();
            }
        };
    }

    /**
     * 管理缓存
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //通过Spring提供的RedisCacheConfiguration类,构造一个自己的redis配置类,从该配置类中可以设置一些初始化的缓存命名空间
        // 及对应的默认过期时间等属性,再利用RedisCacheManager中的builder.build()的方式生成cacheManager:
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();  // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
        config = config.entryTtl(Duration.ofMinutes(1))     // 设置缓存的默认过期时间,也是使用Duration设置
                .disableCachingNullValues();     // 不缓存空值

        // 设置一个初始化的缓存空间set集合
        Set<String> cacheNames = new HashSet<>();
        cacheNames.add("my-redis-cache1");
        cacheNames.add("my-redis-cache2");

        // 对每个缓存空间应用不同的配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("my-redis-cache1", config);
        configMap.put("my-redis-cache2", config.entryTtl(Duration.ofSeconds(120)));

        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)     // 使用自定义的缓存配置初始化一个cacheManager
                .initialCacheNames(cacheNames)  // 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }

}

详细针对下面这段代码进行讲解

在这里插入图片描述
从RedisCacheConfiguration获取一个默认的缓存策略,针对这一策略做对应的调整,生成一个全新的策略。然后,初始化两个缓存槽,赋予名字my-redis-cache1和my-redis-cache2,,赋予再基于之前的缓存策略,初始化两个缓存策略,存储与configMap,然后策略与缓存槽对应上,生成缓存管理器交个spring进行管理,替代掉SSM时代的配置文件。

ssm框架中如果整合redis,那么会有个spring-redis.xml配置文件,其中前面redis链接工厂的创建,已经交于springboot中的application.yml文件来完成。所以,springboot整合redis我们只需要关注下面这部分配置。

在这里插入图片描述

SpringBoot整合redis及其注解式开发

常用缓存注解

@Cacheable:作用是主要针对方法配置,能够根据方法的请求参数对其结果进行缓存

主要参数说明:

  1. value :
    缓存的名称,在 spring 配置文件中定义,必须指定至少一个,
    例如:@Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}。
  2. key :缓存的 key,可以为空,
    如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合,
    例如:@Cacheable(value=”testcache”,key=”#userName”)。
  3. condition :缓存的条件,可以为空,

@CachePut:作用是主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实查询

方法的调用
主要参数说明:
参数配置和@Cacheable一样。

@CacheEvict:作用是主要针对方法配置,能够根据一定的条件对缓存进行清空

主要参数说明:

1、value , key 和 condition 参数配置和@Cacheable一样。
2、allEntries :

是否清空所有缓存内容,缺省为 false,
如果指定为 true,则方法调用后将立即清空所有缓存,
例如:@CachEvict(value=”testcache”,allEntries=true)。

具体代码:

package com.liyingdong.springboot02.service;

import com.liyingdong.springboot02.mapper.BookMapper;
import com.liyingdong.springboot02.model.Book;
import com.liyingdong.springboot02.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;


public interface BookService {
    int deleteByPrimaryKey(Integer bid);
//    存放redis下一次走的还是数据库,只负责存,key是自定义的而不是全包名的那种
      @CachePut(value = "my-redis-cache2",condition="#bid>10",key="'bookid'+#bid")

      //表示使用my-redis-cache1缓存空间,key的生成策略为book+bid,当bid>10的时候才会使用缓存
//    @Cacheable(value = "my-redis-cache1",condition="#bid>10",key="'bookid'+#bid")
    Book selectByPrimaryKey(Integer bid);

    @Cacheable(value = "my-redis-cache1")
    List<Book> listPager(Book book, PageBean pageBean);

//    清除
      @CacheEvict(value = "my-redis-cache2",allEntries = true)
      void clear();


}

BookServiceImpl

package com.liyingdong.springboot02.service.impl;

import com.liyingdong.springboot02.mapper.BookMapper;
import com.liyingdong.springboot02.model.Book;
import com.liyingdong.springboot02.service.BookService;
import com.liyingdong.springboot02.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 李瀛东
 * @site www.xiaomage.com
 * @company xxx公司
 * @create  2020-11-29 19:22
 */
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Override
    public int deleteByPrimaryKey(Integer bid) {
        return bookMapper.deleteByPrimaryKey(bid);
    }

    @Override
    public Book selectByPrimaryKey(Integer bid) {
        return bookMapper.selectByPrimaryKey(bid);
    }

    @Override
    public List<Book> listPager(Book book, PageBean pageBean) {
        return bookMapper.listPager(book);
    }

    @Override
    public void clear() {
        System.out.println("清空对应槽的所有缓存对象");
    }
}

BookServiceImplTest

package com.liyingdong.springboot02.service.impl;

import com.liyingdong.springboot02.model.Book;
import com.liyingdong.springboot02.service.BookService;
import com.liyingdong.springboot02.utils.PageBean;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


/**
 * @author 李瀛东
 * @site www.xiaomage.com
 * @company xxx公司
 * @create  2020-11-29 19:25
 */
@SpringBootTest
class BookServiceImplTest {
    @Autowired
    private BookService bookService;

    @Test
    void deleteByPrimaryKey() {
        System.out.println(bookService.deleteByPrimaryKey(1));
    }

    @Test
    void selectByPrimaryKey() {

        System.out.println(bookService.selectByPrimaryKey(13));
        System.out.println(bookService.selectByPrimaryKey(13));
    }
    @Test
    void listPager() {
        Book book=new Book();
        book.setBname("%圣%");
        PageBean pageBean=new PageBean();
        pageBean.setPage(2);
        for(Book b:bookService.listPager(book,pageBean)){
            System.out.println(b);
        }

    }
    @Test
    void claer() {
        bookService.clear();
    }
}

测试结果:

缓存bid大于10的数据,并且只进行存,不负责取,适用于读写分离。

在这里插入图片描述

redis测试结果
在这里插入图片描述

存储多条数据

在这里插入图片描述
redis测试结果:

在这里插入图片描述
清空所有数据

在这里插入图片描述
redis结果

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,可以使用注解来实现与Redis整合。首先,确保已经在pom.xml中添加了相应的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,需要配置Redis的连接信息,在application.properties或application.yml文件中添加以下配置: ```properties spring.redis.host=your_redis_host spring.redis.port=your_redis_port ``` 然后,在需要使用Redis的类(比如Service或Repository)上添加`@EnableCaching`注解,以启用Spring Cache功能。 接下来,可以在需要使用Redis缓存的方法上使用`@Cacheable`、`@CachePut`、`@CacheEvict`等注解。 - `@Cacheable`:用于在方法执行前,先查询缓存,如果缓存中存在相应的数据,则直接返回;否则执行方法,并将方法的返回值存入缓存中。 - `@CachePut`:用于在方法执行后,将返回值存入缓存中。 - `@CacheEvict`:用于从缓存中移除相应的数据。 例如,下面是一个示例: ```java @Service @EnableCaching public class UserService { @Autowired private UserRepository userRepository; @Cacheable(value = "users", key = "#id") public User getUserById(Long id) { // 从数据库中获取用户信息 return userRepository.findById(id); } @CachePut(value = "users", key = "#user.id") public User saveUser(User user) { // 保存用户信息到数据库 return userRepository.save(user); } @CacheEvict(value = "users", key = "#id") public void deleteUserById(Long id) { // 从数据库中删除用户信息 userRepository.deleteById(id); } } ``` 在上述示例中,`@Cacheable`注解用于根据用户ID查询用户信息,并将查询结果缓存起来;`@CachePut`注解用于保存用户信息到数据库,并将保存后的用户信息存入缓存;`@CacheEvict`注解用于删除用户信息,并同时从缓存中移除相应的数据。 需要注意的是,由于使用了注解缓存,所以必须保证方法的入参和返回值是可序列化的类型,以便正确地进行缓存操作。 这样,你就可以通过注解实现Spring Boot与Redis整合了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值