springboot(4)

springboot配置类

1.注解标签
@Configuration
@Configuration底层是含有@Component ,所以@Configuration 具有和 @Component 的作用。
  @Configuration可理解为用spring的时候xml里面的<beans>标签。
    注: 
  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里面的<bean>标签。
  注: 
  1) @Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同; 
  
  2) @Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域;
  
  3) 既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Repository等注解注册bean(在需要注册的类上加注解),当然需要配置@ComponentScan注解进行自动扫描。

springboot注解类比起之前的ssh、ssm配置文件更加灵活方便

2.redis整合
1.导入redis的依赖
<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
	<dependency>
		<groupId>redis.clients</groupId>
		<artifactId>jedis</artifactId>
	</dependency>

另外为了后面的序列化,我们还需要导入以下依赖:

 <!-- jackson -->
        <jackson.version>2.9.3</jackson.version>
        
<!-- jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        
2.配置application.yml

这里的作用:注册redis.properties
配置jedispool
配置connection

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
3.写redis配置类

创建RedisConfig

配置缓存策略
配置redistemplate

package com.swx.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;

/**
 * @author Songwanxi
 * @site www.lentter.club
 * @company
 * @create  2019-12-30 16:16
 *
 * redis配置类
 */
@Configuration
@EnableCaching//开启注解式缓存
public class RedisConfig extends CachingConfigurerSupport {
    //继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。
    /**
     * 生成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;
    }
}

以上整合redis完成!

3.redis注解式开发
1. @Cacheable

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

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

案例:承接上回的代码,这回只做一些小小的改动
首先是测试的Book类:他要实现Serializable 类

package com.swx.springboot02.entity;

import java.io.Serializable;

public class Book implements Serializable {
    private Integer bid;

    private String bname;

    private Float price;

    public Book(Integer bid, String bname, Float price) {
        this.bid = bid;
        this.bname = bname;
        this.price = price;
    }

    public Book() {
        super();
    }

    public Integer getBid() {
        return bid;
    }

    public void setBid(Integer bid) {
        this.bid = bid;
    }

    public String getBname() {
        return bname;
    }

    public void setBname(String bname) {
        this.bname = bname;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bid=" + bid +
                ", bname='" + bname + '\'' +
                ", price=" + price +
                '}';
    }
}

service层:

package com.swx.springboot02.service;

import com.swx.springboot02.entity.Book;
import com.swx.springboot02.util.PageBean;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;

/**
 * @author Songwanxi
 * @site www.lentter.club
 * @company
 * @create  2019-12-29 19:57
 */
public interface BookService {
    int deleteByPrimaryKey(Integer bid);

    @Cacheable("my-redis-cache1")
    Book selectByPrimaryKey(Integer bid);

    List<Book> selPager(String bname, PageBean pageBean);
}

测试:

package com.swx.springboot02;

import com.swx.springboot02.entity.Book;
import com.swx.springboot02.service.BookService;
import com.swx.springboot02.util.PageBean;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Springboot02Application.class)
public class Springboot02ApplicationTests {
    @Autowired
    private BookService bookService;
    @Test
    public void sel(){
        System.out.println(this.bookService.selectByPrimaryKey(1));
        System.out.println(this.bookService.selectByPrimaryKey(1));
    }
    @Test
    public void del(){
        this.bookService.deleteByPrimaryKey(1);
    }
    @Test
    public void page(){
        PageBean pageBean  = new PageBean();
        List<Book> selpage = this.bookService.selPager("%圣%", pageBean);
        for (Book book : selpage) {
            System.out.println(book);
        }
    }
}

我们试着运行sel()方法,一般来说,sql语句会执行两次,但是在我们加了缓存之后:
在这里插入图片描述
redis中也有了:
在这里插入图片描述
接着我们来测试一个带条件的:

@Cacheable(value = "my-redis-cache1",key = "'id_'+#bid",condition = "#bid > 30")
    Book selectByPrimaryKey(Integer bid);

这里键名我们自定义为id_#bid ,bid是我们穿进去的参数,条件是bid要>30!
在这里插入图片描述
可以看见参数为1小于30,所以没有缓存,我们测试33!
在这里插入图片描述
在这里插入图片描述
有了缓存!

2.@CachePut

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

用于数据的读写分离

我们把注解缓存@CachePut ,条件不变!

@CachePut(value = "my-redis-cache1",key = "'id_'+#bid",condition = "#bid > 30")
    Book selectByPrimaryKey(Integer bid);

在这里插入图片描述
可以看到,即使满足条件也执行了两次sql!

3.@CacheEvict

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

主要参数说明:
  1)value , key 和 condition 参数配置和@Cacheable一样。
  2) allEntries :
  是否清空所有缓存内容,缺省为 false,
  如果指定为 true,则方法调用后将立即清空所有缓存,
  例如:@CachEvict(value=”testcache”,allEntries=true)。 

service层,然后实现它,方法内不需要写任何内容

   @CacheEvict(value = "my-redis-cache2",allEntries = true)
    void cel();

impl

  @Override
    public void cel() {
        System.out.println("一键清除缓存");
    }

测试:

 @Test
    public void cel(){
        this.bookService.cel();
    }

我们缓存一组数据,时间120s
在这里插入图片描述
然后执行cel()!

在这里插入图片描述
在这里插入图片描述
成功清除缓存!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值