springboot中使用redis由浅入深解析

springboot中使用redis由浅入深解析,第1张

概述正文很多时候,我们会在springboot中配置redis,但是就那么几个配置就配好了,没办法知道为什么,这里就详细的讲解一下 @H_419_0@正文

@H_419_0@很多时候,我们会在springboot中配置redis,但是就那么几个配置就配好了,没办法知道为什么,这里就详细的讲解一下
这里假设已经成功创建了一个springboot项目。

@H_419_0@redis连接工厂类

@H_419_0@第一步,需要加上springboot的redis jar包

<dependency>   <groupID>org.springframework.boot</groupID>   <artifactID>spring-boot-starter-data-redis</artifactID></dependency>@H_419_16@@H_419_0@然后我们写一个配置类,创建了一个redis连接的工厂的spring bean。(Redis连接工厂会生成到Redis数据库服务器的连接)

@Configurationpublic class RedisConfig {  @Bean  public RedisConnectionFactory redisCF(){    //如果什么参数都不设置,默认连接本地6379端口    JedisConnectionFactory factory = new JedisConnectionFactory();    factory.setPort(6379);    factory.setHostname("localhost");    return factory;  }}@H_419_16@@H_419_0@单元测试,看看这个工厂方法的使用

@RunWith(SpringJUnit4ClassRunner.class)@SpringBoottest(classes = Application.class)public class RedisTest {    @autowired  RedisConnectionFactory factory;      @Test  public voID testRedis(){    //得到一个连接    RedisConnection conn = factory.getConnection();    conn.set("hello".getBytes(),"world".getBytes());    System.out.println(new String(conn.get("hello".getBytes())));  }}@H_419_16@@H_419_0@输出结果 :world,说明已经成功获取到连接,并且往redis获取添加数据,

@H_419_0@template(模版)

@H_419_0@但是我们发现每次添加的key和value都是byte数组类型(使用很麻烦),于是spring为我们带来了redis template(模版)

@H_419_0@Spring Data Redis提供了两个模板:
  Redistemplate
  StringRedistemplate

@H_419_0@首先我们先创建一个Redistemplate模板类,类型的key是String类型,value是Object类型(如果key和value都是String类型,建议使用StringRedistemplate)

  @Bean  public Redistemplate redistemplate(RedisConnectionFactory factory){    //创建一个模板类    Redistemplate<String,Object> template = new Redistemplate<String,Object>();    //将刚才的redis连接工厂设置到模板类中    template.setConnectionFactory(factory);    return template;  }@H_419_16@@H_419_0@单元测试

@autowired    Redistemplate<String,Object> template;    @Test  public voID testRedistemplate(){    template.opsForValue().set("key1","value1");    System.out.println(template.opsForValue().get("key1"));  }@H_419_16@@H_419_0@得到结果输出value1,是不是很方便了呢。

@H_419_0@ 如果是 *** 作集合呢,也很方便的哈。

  @Test  public voID testRedistemplateList(){      Pruduct prud = new Pruduct(1,"洗发水","100ml");    Pruduct prud2 = new Pruduct(2,"洗面奶","200ml");    //依次从尾部添加元素    template.opsForList().rightPush("pruduct",prud);    template.opsForList().rightPush("pruduct",prud);    //查询索引0到商品总数-1索引(也就是查出所有的商品)    List<Object> prodList = template.opsForList().range("pruduct",template.opsForList().size("pruduct")-1);    for(Object obj:prodList){      System.out.println((Pruduct)obj);    }    System.out.println("产品数量:"+template.opsForList().size("pruduct"));      }@H_419_16@@H_419_0@key和value序列化

@H_419_0@当保存一条数据的时候,key和value都要被序列化成Json数据,取出来的时候被序列化成对象,key和value都会使用序列化器进行序列化,spring data redis提供多个序列化器

@H_419_0@GenericToStringSerializer:使用Spring转换服务进行序列化;
JacksonjsonRedisSerializer:使用Jackson 1,将对象序列化为JsON;
Jackson2JsonRedisSerializer:使用Jackson 2,将对象序列化为JsON;
JdkSerializationRedisSerializer:使用Java序列化;
Oxmserializer:使用Spring O/X映射的编排器和解排器(marshaler和unmarshaler)实现序列化,用于XML序列化;
StringRedisSerializer:序列化String类型的key和value。

@H_419_0@Redistemplate会默认使用JdkSerializationRedisSerializer,这意味着key和value都会通过Java进行序列化。StringRedistemplate默认会使用StringRedisSerializer

@H_419_0@例如,假设当使用Redistemplate的时候,我们希望将Product类型的value序列化为JsON,而key是String类型。Redistemplate的setKeySerializer()和setValueSerializer()方法就需要如下所示:

@Bean  public Redistemplate redistemplate(RedisConnectionFactory factory) {    // 创建一个模板类    Redistemplate<String,Object>();    // 将刚才的redis连接工厂设置到模板类中    template.setConnectionFactory(factory);    // 设置key的序列化器    template.setKeySerializer(new StringRedisSerializer());    // 设置value的序列化器    //使用Jackson 2,将对象序列化为JsON    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);    //Json转对象类,不设置默认的会将Json转成hashmap    ObjectMapper om = new ObjectMapper();    om.setVisibility(PropertyAccessor.ALL,JsonautoDetect.Visibility.ANY);    om.enableDefaultTyPing(ObjectMapper.DefaultTyPing.NON_FINAL);    jackson2JsonRedisSerializer.setobjectMapper(om);    template.setValueSerializer(jackson2JsonRedisSerializer);    return template;  }@H_419_16@@H_419_0@到这里,大家肯定会对springboot使用redis有了简单的了解。

@H_419_0@springboot缓存某个方法

@H_419_0@申明缓存管理器

@H_419_0@在某些时候,我们可能有这样的需求,用户登录的时候,我们会从数据库中读取用户所有的权限,部门等信息。而且每次刷新页面都需要判断该用户有没有这个权限,如果不停的从数据库中读并且计算,是非常耗性能的,所以我们这个时候就要用到了springboot为我们带来的缓存管理器

@H_419_0@首先在我们的RedisConfig这个类上加上@EnableCaching这个注解。

@H_419_0@这个注解会被spring发现,并且会创建一个切面(aspect) 并触发Spring缓存注解的切点(pointcut) 。 根据所使用的注解以及缓存的状态, 这个切面会从缓存中获取数据, 将数据添加到缓存之中或者从缓存中移除某个值。 

@H_419_0@接下来我们需要申明一个缓存管理器的bean,这个作用就是@EnableCaching这个切面在新增缓存或者删除缓存的时候会调用这个缓存管理器的方法

/**   * 申明缓存管理器,会创建一个切面(aspect)并触发Spring缓存注解的切点(pointcut)   * 根据类或者方法所使用的注解以及缓存的状态,这个切面会从缓存中获取数据,将数据添加到缓存之中或者从缓存中移除某个值      * @return   */  @Bean  public RedisCacheManager cacheManager(Redistemplate redistemplate) {    return new RedisCacheManager(redistemplate);  }@H_419_16@@H_419_0@ 当然,缓存管理器除了RedisCacheManager还有一些其他的。例如

SimpleCacheManager NoOpCacheManager ConcurrentMapCacheManager CompositeCacheManager EhCacheCacheManager@H_419_0@ConcurrentMapCacheManager,这个简单的缓存管理器使用java.util.concurrent.ConcurrentHashMap作为其缓存存储。它非常简单,因此对于开发、测试或基础的应用来讲,这是一个很不错的选择.

@H_419_0@添加缓存

@H_419_0@接下来我们在controller层的方法内加上注解,然后启动我们的项目。

@RequestMapPing("/getPrud")  @Cacheable("prudCache")  public Pruduct getPrud(@RequestParam(required=true)String ID){    System.out.println("如果第二次没有走到这里说明缓存被添加了");    return pruductDao.getPrud(Integer.parseInt(ID));  }@H_419_16@@H_419_0@发现打印的这段话只被打印一次,说明在走到这个方法的时候触发了一个切面,并且查找返回缓存中的数据。

@H_419_0@当然@Cacheable注解也可以放到这个dao层的方法里面,但是这里会报一个错,Integer无法转成String,因为我们dao层方法的参数类型是int,而Redistemplate的key类型是String,这里是要注意的。

@H_419_0@打开redis的客户端发现redis对应的key就是我们的参数1,这个时候就会出问题,比如说我在其他要缓存的方法的参数也是1,就会重复。后面我们会将自定义这个key的值。

@H_419_0@除了@Cacheable添加缓存外,springboot还为我们带了了其他几个注解

@H_419_0@删除缓存

@H_419_0@在delete的时候用@Cacheevict清楚这条缓存。

  @RequestMapPing("/deletePrud")  @Cacheevict("pruddeleteCache")  public String deletePrud(@RequestParam(required=true)String ID){    return "SUCCESS";  }@H_419_16@@H_419_0@@CachePut将这个方法的返回值放到缓存,如果我们放一个Pruduct对象,他会将这个对象作为key,这显然不是我们想要的。这个时候就需要自定义我们的key。

@H_419_0@自定义key

@H_419_0@@Cacheable和@CachePut都有一个名为key属性,这个属性能够替换默认的key,它是通过一个表达式(Spel表达式,spring提供的,很简单)计算得到的。

@H_419_0@例如下面的就是将返回对象的ID当作key来存储(但是Pruduct的ID是int类型,所以需要将数字转化成String类型)

  @RequestMapPing("/savePrud")  @CachePut(value="prudsaveCache",key="#result.ID +''")  public Pruduct savePrud(Pruduct prud){    return prud;  }@H_419_16@@H_419_0@另外除了#result是代表函数的返回值,spring还为我们带来了其他的一些元数据

@H_419_0@ 条件化缓存

@H_419_0@通过为方法添加Spring的缓存注解,Spring就会围绕着这个方法创建一个缓存切面。但是,在有些场景下我们可能希望将缓存功能关闭。

@H_419_0@@Cacheable和@CachePut提供了两个属性用以实现条件化缓存:unless和condition,这两个属性都接受一个SpEL表达式。如果unless属性的SpEL表达式计算结
果为true,那么缓存方法返回的数据就不会放到缓存中。与之类似,如果condition属性的SpEL表达式计算结果为false,那么对于这个方法缓存就会被禁用掉

@H_419_0@表面上来看,unless和condition属性做的是相同的事情。但是,这里有一点细微的差别。

@H_419_0@unless属性只能阻止将对象放进缓存,但是在这个方法调用的时候,依然会去缓存中进行查找,如果找到了匹配的值,就会返回找到的值。

@H_419_0@与之不同,如果condition的表达式计算结果为false,那么在这个方法调用的过程中,缓存是被禁用的。就是说,不会去缓存进行查找,同时返回值也不会放进缓存中。

  @RequestMapPing("/getPrud2")  @CachePut(value ="prudCache",unless="#result.desc.contains('nocache')")  public Pruduct getPrud2(@RequestParam(required=true)String ID){    System.out.println("如果走到这里说明,说明缓存没有生效!");    Pruduct p = new Pruduct(Integer.parseInt(ID),"name_nocache"+ID,"nocache");    return p;  }  @H_419_16@@H_419_0@上面的代码中,如果返回的对象desc中包含nocache字符串,则不进行缓存。

@H_419_0@总结demo:

@H_419_0@将类名方法名和pruduct的ID作为key

@RequestMapPing("/getPrud3")  @Cacheable(value ="prudCache",key="#root.targetClass.getname() + #root.methodname + #ID")  public Pruduct getPrud3(@RequestParam(required=true)String ID){    System.out.println("如果第二次没有走到这里说明缓存被添加了");    return pruductDao.getPrud(Integer.parseInt(ID));  }@H_419_16@@H_419_0@最后注意

@H_419_0@#result 方法返回值不能用在@Cacheable上,只能用在@CachePut

@H_419_0@springboot配置升级简单化

@H_419_0@当然上面的配置只是为了了解原理的哈,实际上我们使用会更简单点。我们重写了RedisConfig

@H_419_0@

@Configuration@EnableCaching//开启缓存public class RedisConfig extends CachingConfigurerSupport {  @Bean  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();      }    };  }    /**   * 申明缓存管理器,会创建一个切面(aspect)并触发Spring缓存注解的切点(pointcut)   * 根据类或者方法所使用的注解以及缓存的状态,这个切面会从缓存中获取数据,将数据添加到缓存之中或者从缓存中移除某个值      * @return   */  @Bean  public RedisCacheManager cacheManager(Redistemplate redistemplate) {    return new RedisCacheManager(redistemplate);  }  @Bean  @Primary  public Redistemplate redistemplate(RedisConnectionFactory factory) {    // 创建一个模板类    Redistemplate<String,JsonautoDetect.Visibility.ANY);    om.enableDefaultTyPing(ObjectMapper.DefaultTyPing.NON_FINAL);    jackson2JsonRedisSerializer.setobjectMapper(om);    template.setValueSerializer(jackson2JsonRedisSerializer);    return template;  }}@H_419_16@@H_419_0@然后在resources下的application.propertIEs下配置

# REdis (RedisPropertIEs)# Redis数据库索引(默认为0)spring.redis.database=0 # Redis服务器地址spring.redis.host=127.0.0.1# Redis服务器连接端口spring.redis.port=6379 # Redis服务器连接密码(默认为空)spring.redis.password=# 连接池最大连接数(使用负值表示没有限制)spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接spring.redis.pool.max-IDle=8 # 连接池中的最小空闲连接spring.redis.pool.min-IDle=0 # 连接超时时间(毫秒)spring.redis.timeout=0@H_419_16@@H_419_0@大家发现我们并没有注册RedisConnectionFactory,那是因为spring默认帮我们读取application.propertIEs文件并且注册了一个factorybean

@H_419_0@keyGenerator方法帮我们注册了一个key的生成规则,就不用我们写spel表达式了,根据反射的原理读取类名+方法名+参数。但是我们有时候还是需要结合spel的。

@H_419_0@然后在controller上加上@Cacheable("cachename"),之后就可以在redis看到保存了并且key的值是keyGenerator生成的名字

@H_419_0@本文代码github地址

@H_419_0@以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的springboot中使用redis由浅入深解析全部内容,希望文章能够帮你解决springboot中使用redis由浅入深解析所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1227432.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存