Springboot-整合redis

Redis的三种加载配置方式

Spring Boot中共有三种加载Redis配置的方式:

  • AutoConfig加载
  • 自己写代码加载
  • xml加载
  • 本文只介绍前面两种

一、添加依赖

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

二、配置文件

spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.timeout=10000

spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1

三、AutoConfig加载代码配置

import java.net.UnknownHostException;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfiguration {
    
    /*
     * @Bean
     *
     * @ConditionalOnMissingBean(name = "redisTemplate") public
     * RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory
     * redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object,
     * Object> template = new RedisTemplate<Object, Object>();
     * template.setConnectionFactory(redisConnectionFactory); return template; }
     */

      /**
       * redis模板,存储关键字是字符串,值是Jdk序列化
       * @Description:
       * @param factory
       * @return
       */
      @Bean
      @ConditionalOnMissingBean(name = "redisTemplate")
      public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory) {
          RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
          redisTemplate.setConnectionFactory(factory);
          RedisSerializer<String> redisSerializer = new StringRedisSerializer();
          redisTemplate.setKeySerializer(redisSerializer);
          redisTemplate.setHashKeySerializer(redisSerializer);
          //JdkSerializationRedisSerializer序列化方式;
          JdkSerializationRedisSerializer jdkRedisSerializer=new JdkSerializationRedisSerializer();
          redisTemplate.setValueSerializer(jdkRedisSerializer);
          redisTemplate.setHashValueSerializer(jdkRedisSerializer);
          redisTemplate.afterPropertiesSet();
          return redisTemplate;
      }
    
    
    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory)
                    throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

第四步、测试

import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.yatai.visitor.Application;
import com.yatai.visitor.domain.Person;

@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestRedis {
    
        @Resource
        private RedisTemplate<String, Object> redisTemplate;
       
        @Test
        public void testSet() {
        /*
         * this.redisTemplate.opsForValue().set("study", "java");
         * System.out.println(thais.redisTemplate.opsForValue().get("study"));
         */
            //记得将此类实现序列化
         //   Person p=new Person();
         //   p.setName("张三");
         //   p.setAge(22);
        //    p.setSex("男");
            
      //       this.redisTemplate.opsForValue().set("study1", p);
       //     System.out.println(this.redisTemplate.opsForValue().get("study1"));
            
        }
}

测试中的实体类

  import java.io.Serializable;

public class Person implements Serializable{
    
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private String name;
    
    private int age;
    
    private String sex;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

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

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }
    
    
}

五、以上步骤整合成功,亲测有效 ,这是单机版模式

六、自己写代码配置

@Configuration
public class RedisConfig{

  private Logger logger = LoggerFactory.getLogger(this.getClass());

  @Value("${spring.redis.host}")
  private String host;

  @Value("${spring.redis.port}")
  private int port;

  @Value("${spring.redis.timeout}")
  private int timeout;

  @Value("${spring.redis.password}")
  private String password;

  @Value("${spring.redis.database}")
  private int database;

  @Value("${spring.redis.pool.max-idle}")
  private int maxIdle;

  @Value("${spring.redis.pool.min-idle}")
  private int minIdle;

  /**
   * redis模板,存储关键字是字符串,值是Jdk序列化
   * @Description:
   * @param factory
   * @return
   */
  @Bean
  public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory) {
      RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
      redisTemplate.setConnectionFactory(factory);
      RedisSerializer<String> redisSerializer = new StringRedisSerializer();
      redisTemplate.setKeySerializer(redisSerializer);
      redisTemplate.setHashKeySerializer(redisSerializer);
      //JdkSerializationRedisSerializer序列化方式;
      JdkSerializationRedisSerializer jdkRedisSerializer=new JdkSerializationRedisSerializer();
      redisTemplate.setValueSerializer(jdkRedisSerializer);
      redisTemplate.setHashValueSerializer(jdkRedisSerializer);
      redisTemplate.afterPropertiesSet();
      return redisTemplate;
  }
}

springboot 对redis整合以上就是这样,工具类可自行封装。

原文地址:https://www.cnblogs.com/hellohero55/p/11218447.html