Springboot整合redis(lettuce)

13 篇文章 3 订阅
4 篇文章 0 订阅

springboot 整合redis(lettuce)

首先确保电脑上装了redis。最好能用redisDesktop查看一下数据情况

  1. redis是一款非常流行的Nosql数据库。redis的功能非常强大,因为Nosql在查询上的速度特别快。(在算法上的hash和数组查询的差距)在web上常用作缓存(消息队列等)。本文只介绍redis和springboot的集成,不介绍缓存部分下文将介绍缓存部分。
  2. 目前流行的redis集成到java环境有jedis和lettuce。在之前版本中jedis可能更受青睐。但是在springboot2.0之后官方推荐的默认就是lettuce连接。因为jedis数据池虽然线程安全,但是占用的资源较大,而lettuce基于netty和nio相关实现,性能更加强悍,占用的资源也比较少,并且使用起来也不难。
  3. redis默认有16个分区(表),不配置情况默认用0个
  4. 项目采取lettuce方式整合redis。lettuce性能更强点,喜欢jedis配合连接池也是线程安全的
  5. redis 默认五种基本类型:String,set,hash,zset(有序集合),list
  6. spring中redis 有StringRedisTemplate和RedisTemplate
  • 对于StringRedisTemplate,继承RedisTemplate,只能存String类型的数据。不方面存对象,一般用的不是特别多(特定场景除外)。
    比较麻烦,存入的key和value都是字符型。
  • 对于RedisTemplate,默认是类型。如果不做配置,他会对key和value默认序列化成二进制文件看不懂。不利于观察。一般重新配置redisTeamplate的一个bean。设置这个bean的key,value, 以及hashkey等等的序列化方式。**一般是key序列化为string,value序列化为json,**这样,你就可以在存入对象时候它自动帮你序列化成字符或者json。方便观察。
  1. 对于整合redis你只需pom.xml引入相应依赖。在application.properties中填写相应配置
    账号密码之类。在重写RedisTemplate这个bean。配置他的序列化规则。注意就是注入bean的时候名称要和重写的名一样。因为这个对象是 spring帮你生成好的给你使用。而如果你随便瞎起名字的话spring会根据原始重新生成对象。相当于引用未序列化的redisTemplate。
  2. 更多的用法请百度。如果要存对象,那么pojo一定要继承序列化。否则无法存入redis。至于redis缓存,将在整合Springcache中介绍
  3. 确保有无参构造方法继承序列化

springboot官方的整合redis这么说的
10. You can also register an arbitrary number of beans that implement LettuceClientConfigurationBuilderCustomizer for more advanced customizations. If you use Jedis, JedisClientConfigurationBuilderCustomizer is also available.
11. If you add your own @Bean of any of the auto-configured types, it replaces the default (except in the case of RedisTemplate, when the exclusion is based on the bean name, redisTemplate, not its type). By default, if commons-pool2 is on the classpath, you get a pooled connection factory.

项目的目录为
在这里插入图片描述
12. 首先,在创建Springboot项目时候勾选redis选项或者在pom.xml中添加:

 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>
 <dependency>
  <groupId>org.apache.commons</groupId>
 <artifactId> commons-pool2</artifactId>
 </dependency>
  1. 在application.properties添加一下配置:

spring.redis.host=127.0.0.1
spring.redis.password=
spring.redis.port= 6379
spring.redis.timeout=10000
spring.cache.type=redis

# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
spring.redis.database=2
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0
  1. redis默认模板只能存储,你也可以用但是每次都要转成json字符串传输可能很麻烦,这样你可以重写一个模板程序自动加载,可以存 . 这是一个很重要的加载类,它声明redis存储类型:
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfiguration {
    @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        // 设置键(key)的序列化采用StringRedisSerializer。
        template.setKeySerializer(new StringRedisSerializer());
        // 设置值(value)的序列化采用jackson的序列化。
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}
  1. redisTest如下:
    user类:
package com.redis.pojo;

import java.io.Serializable;

public class user implements Serializable {

 //private static final Long
 private String name;
 private String password;
 private String sex;

 public user(){}
 @Override
 public String toString() {
 return "name:" name " password" password " sex" sex;
 }

 public user(String name, String password, String sex)
 {
 this.name=name;
 this.password=password;
 this.sex=sex;
 }
 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getPassword() {
 return password;
 }

 public void setPassword(String password) {
 this.password = password;
 }

 public String getSex() {
 return sex;
 }

 public void setSex(String sex) {
 this.sex = sex;
 }
}

controller

import com.redis.pojo.user;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class redisController {
    private  final static Logger log= LoggerFactory.getLogger(redisController.class);
    /*
    注入的名称要和RedisConfiguration的名称一致
    否则注入的默认的redisTemplate
    如果不喜欢序列化可以直接给config文件夹删除,哈哈
     */
    @Autowired(required = false)
    RedisTemplate redisCacheTemplate;
    //如果RedisTemplate redisTemplate就相当没配置序列化等
    @Autowired(required = false)
    StringRedisTemplate stringRedisTemplate;

    @Autowired(required = false)
    RedisTemplate redisTemplate;

    @GetMapping("test1")//StringRedistemplate  存String
    public String test1()
    {
        stringRedisTemplate.opsForValue().set("test1","hello赛赛");//再desttop中可以看到为中文串
        stringRedisTemplate.opsForValue().set("redis:test1","hello赛赛");//再desttop中可以看到为中文串
        redisTemplate.opsForValue().set("test1","hello赛赛");//再desttop中可以看到为二进制数字乱起八糟
        String val1=stringRedisTemplate.opsForValue().get("test1");
        //String va2=(String) redisCacheTemplate.opsForValue().get("test1");//不注释会报异常,因为Stingxxtemplate就是String没有序列化过。反序列化会报异常
        log.info(val1+" ");
        return val1+"      ";

    }
    @GetMapping("test2")//Redistemplate   存String
    public String test2()
    {
        redisCacheTemplate.opsForValue().set("bigsai222","hello赛赛2");
        String val1=stringRedisTemplate.opsForValue().get("bigsai222");//为  "hello赛赛2" 多个引号
        String va2=(String) redisCacheTemplate.opsForValue().get("bigsai222");//为  hello赛赛2  没有引号因为json反序列化
        log.info(val1+" "+va2);
        return val1+"      "+va2;
    }

    @GetMapping("test3")
    public user test3()
    {
        user user=new user("大佬","点个star谢谢!","man");
        redisCacheTemplate.opsForValue().set("user",user);
        user value=(user) redisCacheTemplate.opsForValue().get("user");
       log.info(redisCacheTemplate.hasKey("user")+"");//判断是否有键值对
       return value;
    }
}

test类

package com.redis;

import com.redis.pojo.user;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.Serializable;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisApplicationTests {

 private final static Logger log= LoggerFactory.getLogger(RedisApplicationTests.class);
 @Autowired(required = false)
 RedisTemplate redisCacheTemplate;
 @Autowired(required = false)
 RedisTemplate redisTemplate;
 @Test
 public void contextLoads() {
 }
 @Test
 public void test1()
 {
 redisCacheTemplate.opsForValue().set("hello","heoolo");
 log.warn((String) redisCacheTemplate.opsForValue().get("hello"));

 }
 @Test
 public void test2()
 {
 user usr=new user("66","赛格","man");
 redisCacheTemplate.opsForValue().set("bigsai",usr);
 user user2=(user) redisCacheTemplate.opsForValue().get("bigsai");
 log.warn(user2.toString());
 }
 @Test
 public void test3()
 {
 user usr=new user("66","赛格","man");
 redisTemplate.opsForValue().set("bigsai33",usr);
 user user2=(user) redisTemplate.opsForValue().get("bigsai33");
 log.warn(user2.toString());
 }

}

  1. 访问test1,你可以大概看到对象
    测试情况:在这里插入图片描述
  • 还有其他的test和controller可以自行访问体验其中差异。最好用redis的客户端工具观察。
  • 如果不想配置序列化直接使用即可,不需要redis配置类(不利于观察不推荐)!
  • 你可以看到已经成功了,但是你可能会发现redis存储对象的方式是json格式。其实redis本身不支持object类型对象,我们通过中间json达到存储object效果。
  • 你可能还会有疑问,为啥redis模板不是而是。这就涉及到java传输信息时候的序列化和接收的反序列化。他可以完美的序列化,反序列化。关于序列化的意义和内容更多可以百度,在声明User类的时候,它继承了序列化接口,那么可以直接这样写。这个思想可以了解下java面向对象继承的向上继承和向下继承。
  • 另外,redis还可以操作一些其他类型
  • 下列的就是Redis其它类型所对应的操作方式:
    opsForValue: 对应 String(字符串)
    opsForZSet: 对应 ZSet(有序集合)
    opsForHash: 对应 Hash(哈希)
    opsForList: 对应 List(列表)
    opsForSet: 对应 Set(集合)
    opsForGeo: 对应 GEO(地理位置)

那么springboot和mybatis,redis已经整合完毕了。你可以在项目中存取一些适合key-value的数值,并且使用起来相比mysql也要方便一些。

项目github地址

如果描述错误还请大佬指正?!

  • 如果对后端、爬虫、数据结构算法等感性趣欢迎关注我的个人公众号交流:bigsai
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员bigsai

喝杯咖啡压压惊!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值