Redis学习之SpringBoot整合Redis

  • SpringBoot官网地址
  • SpringBoot整合Redis依赖引入
  • 注意事项
  • 搭建问题
  • SpringBoot1.x整合SpringDataRedis
  • SpringBoot2.x整合SpringDataRedis
  • Spring整合SpringDataRedis和Jedis
  • 注意事项


SpringBoot官网地址

https://spring.io/projects/spring-boot

SpringBoot整合Redis依赖引入

  • 查找对应SpringBoot版本
  • redission springboot redission springboot 版本匹配_Redis

  • SpringBoot版本介绍
    GA:General Availability,正式发布的版本,官方推荐使用此版本。在国外都是用GA来说明release版本的。
    PRE: 预览版,内部测试版. 主要是给开发人员和测试人员测试和找BUG用的,不建议使用;
    SNAPSHOT: 快照版,可以稳定使用,且仍在继续改进版本
  • 点击对应版本官方文档
  • 选中Starters
  • redission springboot redission springboot 版本匹配_Redis_02

  • 找到需要引入依赖的artifactId
  • redission springboot redission springboot 版本匹配_redis_03

  • 引入依赖
<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
  • IDEA查看引入依赖中引用的依赖
    Ctrl + 鼠标左键
  • redission springboot redission springboot 版本匹配_spring_04

注意事项

  • Redis操作客户端依赖变更
    在springboot1.x系列中,其中使用的是jedis,但是到了springboot2.x其中使用的是Lettuce。 此处springboot2.x,所以使用的是Lettuce。
  • jedis跟lettuce的区别
  1. Lettuce 和 Jedis 的定位都是Redis的client,所以他们当然可以直接连接redis server。
  2. Jedis在实现上是直接连接的redis server,如果在多线程环境下是非线程安全的,这个时候只有使用连接池,为每个Jedis实例增加物理连接
  3. Lettuce的连接是基于Netty的,连接实例(StatefulRedisConnection)可以在多个线程间并发访问,应为StatefulRedisConnection是线程安全的,所以一个连接实例(StatefulRedisConnection)就可以满足多线程环境下的并发访问,当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。
  • 参考链接

搭建问题

SpringBoot1.x整合SpringDataRedis

  • 参考链接

SpringBoot2.x整合SpringDataRedis

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
		<!--<exclusions>-->
			<!--<exclusion>-->
				<!--<groupId>org.junit.vintage</groupId>-->
				<!--<artifactId>junit-vintage-engine</artifactId>-->
			<!--</exclusion>-->
		<!--</exclusions>-->
	</dependency>

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

    <!-- redis依赖commons-pool 这个依赖一定要添加 -->
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-pool2</artifactId>
	</dependency>
  • 编写application.properties配置文件
# Redis数据库索引(默认为0)
    spring.redis.database=0
    # Redis服务器地址
    spring.redis.host=192.168.159.133
    # Redis服务器连接端口
    spring.redis.port=6379
    # Redis服务器连接密码(默认为空)
    spring.redis.password=redispassword
    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.lettuce.pool.max-active=8
    # 连接池中的最大空闲连接
    spring.redis.lettuce.pool.max-idle=8
    #最大建立连接等待时间。如果超过此时间将接到异常(使用负值表示没有限制)
    spring.redis.lettuce.pool.max-wait=5000
    # 连接池中的最小空闲连接
    spring.redis.lettuce.pool.min-idle=0
  • 案例代码
  1. User类
@Data
     public class User implements Serializable {


         private static final long serialVersionUID = 2026068246662654437L;

         private Long id;

         private String name;

         private Integer age;

         private String sex;
     }
  1. 接口及实现类
public interface UserService {

         public String getUserName();

         public User getUserById();
     }


     @Service
     public class UserServiceImpl implements UserService {

         @Autowired
         private StringRedisTemplate stringRedisTemplate;

         @Autowired
         private RedisTemplate<Object,Object> redisTemplate;

         @Override
         public String getUserName() {
             String name = stringRedisTemplate.opsForValue().get("student");

             return name;
         }

         @Override
         public User getUserById() {
             User result = null;

             if (redisTemplate.hasKey("user:3")) {

                 System.out.println("------------从缓存中查询-------------");
                 result = (User) redisTemplate.opsForValue().get("user:3");

             } else {
                 System.out.println("------------从数据库中查询-------------");
                 User user = new User();
                 user.setId(3l);
                 user.setAge(25);
                 user.setName("张三");
                 user.setSex("男");
                 result = user;
                 redisTemplate.opsForValue().set("user:3",user);
                 
             }

             return result;
         }
     }
  1. 自定义Redis配置类
@Configuration
     public class MyRedisConfig {


         /**
         * 使用LettuceConnectionFactory创建RedisTemplate:用于执行Redis操作的方法
         */
         @Bean
         public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory factory){

             RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();

             //关联
             template.setConnectionFactory(factory);

             //使用Jackson2JsonRedisSerializer序列化器
             Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
             //ObjectMapper 是一个使用 Swift 编写的用于 model 对象(类和结构体)和 JSON 之间转换的框架
             ObjectMapper objectMapper = new ObjectMapper();
             objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
             objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
             jsonRedisSerializer.setObjectMapper(objectMapper);
     //        template.setDefaultSerializer(jsonRedisSerializer);

             //使用StringRedisSerializer来序列化和反序列化redis的key值
             RedisSerializer redisSerializer = new StringRedisSerializer();
             //key
             template.setKeySerializer(redisSerializer);
             template.setHashKeySerializer(redisSerializer);

             //value
             template.setValueSerializer(jsonRedisSerializer);
             template.setHashValueSerializer(jsonRedisSerializer);

     //        template.setDefaultSerializer(new Jackson2JsonRedisSerializer<Object>());
             template.afterPropertiesSet();
             return template;
         }
     }
  1. 启动类
@SpringBootApplication
     public class ShopRedisServiceApplication {

         public static void main(String[] args) {
             SpringApplication.run(ShopRedisServiceApplication.class, args);
         }

     }
  1. 测试类
@RunWith(SpringRunner.class)
     @SpringBootTest(classes = ShopRedisServiceApplication.class)
     public class ShopRedisServiceApplicationTests {


         @Autowired
         private UserService userService;

         @Test
         public void testGetStr(){

             String name = userService.getUserName();

             System.out.println("你好啊:" + name);
         }

         @Test
         public void testGetObj(){
             User user = userService.getUserById();
             System.out.println(user.toString());
         }

     }

Spring整合SpringDataRedis和Jedis

  • 引入依赖
<!-- 引入jedis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.4.2</version>
    </dependency>
    <!-- redis整合SpringData -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.4.2.RELEASE</version>
    </dependency>
  • 配置
  • redission springboot redission springboot 版本匹配_spring_05

注意事项

  • 序列化器选择
    把任何数据保存到redis中,都需要经过序列化,默认使用JdkSerializationRedisSerializer进行序列化。JdkSerializationRedisSerializer会对所有的key和value还有hashkey和hashvalue的原始字符前,都加了一串字符串。
  • redisTemplate 和 StringRedisTemplate已被自动配置
//源码类
    org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
  • SpringBoot2.x添加commons-pool2依赖
// 未添加报错
    Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig
  • 使用IntelliJ IDEA自动生成serialVersionUID