springboot整合Redis详解完整篇


我们现在项目大都使用springboot,那如何在springboot中加入redis呢?
主要有以下这几步:

1.需要加入Redis的依赖Jar,代码为:

<! -redis依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>${spring-boot.version}</version> 
</dependency>

2.只需要在配置文件application.properties中加入Redis的连接配置即可

# Redis数据库索引(默认为0)  
spring.redis.database=0  
# Redis服务器地址  
spring.redis.host=192.168.0.24  
# Redis服务器连接端口  
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)  
spring.redis.password=  
# 连接池最大连接数(使用负值表示没有限制)  
spring.redis.pool.max-active=200  
# 连接池最大阻塞等待时间(使用负值表示没有限制)  
spring.redis.pool.max-wait=-1  
# 连接池中的最大空闲连接  
spring.redis.pool.max-idle=10 
# 连接池中的最小空闲连接  
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)  
spring.redis.timeout=1000

3.Redis自定义注入bean组件配置

对于Spring Boot项目整合Redis,最主要的Bean操作组件莫过于RedisTemplate跟StringRedisTemplate,后者其实是前者的一种特殊体现。而在项目中使用Redis的过程中,一般情况下是需要自定义配置上述两个操作Bean组件的,比如指定缓存中Key与Value的序列化策略等配置。以下代码为自定义注入配置操作组件RedisTemplate与StringRedis-Template相关属性:

package com.coding.fight.server.config;
        //导入包
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.core.env.Environment;
        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.JdkSerializationRedis
        Serializer;
        import org.springframework.data.redis.serializer.StringRedisSerializer;
        //通用化配置
        @Configuration
        public class CommonConfig {
            //Redis链接工厂
            @Autowired
            private RedisConnectionFactory redisConnectionFactory;
            //缓存操作组件RedisTemplate的自定义配置
            @Bean
        public RedisTemplate<String, Object> redisTemplate(){
          //定义RedisTemplate实例
              RedisTemplate<String, Object> redisTemplate=new RedisTemplate
        <String, Object>();
          //设置Redis的链接工厂
              redisTemplate.setConnectionFactory(redisConnectionFactory);
              //TODO:指定大Key序列化策略为String序列化,Value为JDK自带的序列化策略
              redisTemplate.setKeySerializer(new StringRedisSerializer());
              redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
              //TODO:指定hashKey序列化策略为String序列化-针对hash散列存储
              redisTemplate.setHashKeySerializer(new StringRedisSerializer());
              return redisTemplate;
            }
            //缓存操作组件StringRedisTemplate
            @Bean
            public StringRedisTemplate stringRedisTemplate(){
              //采用默认配置即可-后续有自定义配置时则在此处添加即可
              StringRedisTemplate stringRedisTemplate=new StringRedisTemplate();
              stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
              return stringRedisTemplate;
            }
        }

上述代码中对于RedisTemplate自定义注入配置的属性主要是缓存中Key与Value的序列化策略;对于StringRedisTemplate则采用默认的配置,后续如果有自定义的配置时则可以在此处添加。

4.1RedisTemplate实战**

演示RedisTemplate操作组件的应用

  1. 采用RedisTemplate将字符串信息写入缓存中,并读取出来展示到控制台上。
  2. 采用RedisTemplate将对象信息序列化为JSON格式的字符串后写入缓存中,然后将其读取出来,最后反序列化解析其中的内容并展示在控制台上。
//1.
package com.debug.middleware.server;
        //导入包
        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.data.redis.core.ValueOperations;
        import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
        //单元测试类
        @RunWith(SpringJUnit4ClassRunner.class)
        @SpringBootTest
        public class RedisTest {
            //定义日志
            private static final Logger log= LoggerFactory.getLogger(RedisTest.
        class);
            //由于之前已经自定义注入RedisTemplate组件,因而在此可以直接自动装配
            @Autowired
            private RedisTemplate redisTemplate;
            //采用RedisTemplate将字符串信息写入缓存中并读取出来
            @Test
            public void one(){
              log.info("------开始RedisTemplate操作组件实战----");
              //定义字符串内容及存入缓存的key
              final String content="RedisTemplate实战字符串信息";
              final String key="redis:template:one:string";
              //Redis通用的操作组件
              ValueOperations valueOperations=redisTemplate.opsForValue();
              //将字符串信息写入缓存中
              log.info("写入缓存中的内容:{} ", content);
              valueOperations.set(key, content);
              //从缓存中读取内容
              Object result=valueOperations.get(key);
              log.info("读取出来的内容:{} ", result); 
              }
         }
2.
package com.debug.middleware.server;
        //导入包
        import com.debug.middleware.server.entity.User;
        import com.fasterxml.jackson.databind.ObjectMapper;
        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.data.redis.core.ValueOperations;
        import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
        //单元测试类
        @RunWith(SpringJUnit4ClassRunner.class)
        @SpringBootTest
        public class RedisTest {
            //定义日志
            private static final Logger log= LoggerFactory.getLogger(RedisTest.class);
            //定义RedisTemplate操作组件
            @Autowired
            private RedisTemplate redisTemplate;
            //定义JSON序列化与反序列化框架类
            @Autowired
            private ObjectMapper objectMapper;
            //采用RedisTemplate将对象信息序列化为JSON格式字符串后写入缓存中
            //然后将其读取出来,最后反序列化解析其中的内容并展示在控制台上
            @Test
            public void two() throws Exception{
            log.info("------开始RedisTemplate操作组件实战----");
            //构造对象信息
            User user=new User(1, "debug", "阿修罗");
            //Redis通用的操作组件
            ValueOperations valueOperations=redisTemplate.opsForValue();
            //将序列化后的信息写入缓存中
            final String key="redis:template:two:object";
            final String content=objectMapper.writeValueAsString(user);
            valueOperations.set(key, content);
            log.info("写入缓存对象的信息:{} ", user);
            //从缓存中读取内容
            Object result=valueOperations.get(key);
            if (result! =null){
                User resultUser=objectMapper.readValue(result.toString(), User.class);
                log.info("读取缓存内容并反序列化后的结果:{} ", resultUser);
            }
        }

4.2StringRedisTemplate实战

StringRedisTemplate用于操作字符串类型的数据信息。

/定义StringRedisTemplate操作组件
@Autowired
 private StringRedisTemplate stringRedisTemplate;
 //采用StringRedisTemplate将字符串信息写入缓存中并读取出来
 @Test
 public void three(){
     log.info("------开始StringRedisTemplate操作组件实战----");
     //定义字符串内容及存入缓存的key
     final String content="StringRedisTemplate实战字符串信息";
     final String key="redis:three";
     //Redis通用的操作组件
     ValueOperations valueOperations=stringRedisTemplate.opsForValue();
     //将字符串信息写入缓存中
     log.info("写入缓存中的内容:{} ", content);
     valueOperations.set(key, content);
     //从缓存中读取内容
     Object result=valueOperations.get(key);
     log.info("读取出来的内容:{} ", result);
 }
//采用StringRedisTemplate将对象信息序列化为JSON格式字符串后写入缓存中
//然后将其读取出来,最后反序列化解析其中的内容并展示在控制台上
@Test
public void four() throws Exception{
    log.info("------开始StringRedisTemplate操作组件实战----");
    //构造对象信息
    User user=new User(2, "SteadyJack", "阿修罗");
    //Redis通用的操作组件
    ValueOperations valueOperations=redisTemplate.opsForValue();
    //将序列化后的信息写入缓存中
    final String key="redis:four";
    final String content=objectMapper.writeValueAsString(user);
    valueOperations.set(key, content);
    log.info("写入缓存对象的信息:{} ", user);
    //从缓存中读取内容
    Object result=valueOperations.get(key);
    if (result! =null){
        User resultUser=objectMapper.readValue(result.toString(), User.class);
        log.info("读取缓存内容并反序列化后的结果:{} ", resultUser);
    }
}
  • 33
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值