美文网首页全面攻略SpringBoot
SpringBoot整合Redis作为缓存(一)

SpringBoot整合Redis作为缓存(一)

作者: Invi | 来源:发表于2019-05-05 17:02 被阅读0次

Spring使用redis

Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。

1.安装redis

参考:https://www.cnblogs.com/feijl/p/6879929.html

2.pom.xml引入redis的starter依赖

pom.xml 添加新的依赖

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

2.application.properties 配置redis

application.properties 添加链接redis配置:

#配置redis地址
spring.redis.host=127.0.0.1

查看自动注入的redis配置类

3.RedisAutoConfiguration

RedisAutoConfiguration 配置类

引入redis后RedisAutoConfiguration就起作用了、并且添加了两个组件:

  • RedisTemplate<Object, Object>
  • StringRedisTemplate
package org.springframework.boot.autoconfigure.data.redis;

@Configuration
@ConditionalOnClass({ JedisConnection.class, RedisOperations.class, Jedis.class })
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {
    
    .....
    

    /**
     * Standard Redis configuration.
     */
    @Configuration
    protected static 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;
        }

        @Bean
        @ConditionalOnMissingBean(StringRedisTemplate.class)
        public StringRedisTemplate stringRedisTemplate(
                RedisConnectionFactory redisConnectionFactory)
                throws UnknownHostException {
            StringRedisTemplate template = new StringRedisTemplate();
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }

    }

}

RedisTemplate<Object, Object> 用于对象的操作

StringRedisTemplate 用于string操作

4.测试redis

stringRedisTemplate的使用

创建测试方法:


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 功能描述:测试保存String,List,Set,Hash(散列),Zset(有序集合)
     * stringRedisTemplate.opsForValue() - 操作String
     * stringRedisTemplate.opsForHash() - 操作Hash
     * stringRedisTemplate.opsForList() - 操作List
     * stringRedisTemplate.opsForZSet() - 操作Zset
     * stringRedisTemplate.opsForSet() - 操作Set
     */
    @Test
    public void test1() {
        //添加数据
        //stringRedisTemplate.opsForValue().append("msg", "hellWord!");
        //读取数据
        String msg = stringRedisTemplate.opsForValue().get("msg");
        System.out.println("msg:" + msg);


        //添加List
        stringRedisTemplate.opsForList().leftPush("Spring-redis-test-list", "value1");
        stringRedisTemplate.opsForList().leftPush("Spring-redis-test-list", "value2");
        stringRedisTemplate.opsForList().leftPush("Spring-redis-test-list", "value3");
    }
    

5.自定义redisTemplate的使用

默认RedisTemplate<Object, Object> 使用JDK进行序列化,存储到redis中会出现特殊乱码,我们使用JSON序列化对象后存储。

在配置类中为一个对象创建指定的 RedisTemplate 操作redis。

创建配置类:

package com.invi.cache.config;

import com.invi.cache.bean.Employee;
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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.net.UnknownHostException;

/**
 * @version V7.0
 * @date 2019-02-27 16:34
 * @description
 */


@Configuration
public class CustomRedisConfig {

    @Bean/**("employeeRedisTemplate")**/
    public RedisTemplate<Object, Employee> employeeRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Employee> employeeRedisTemplate = new RedisTemplate<Object, Employee>();
        employeeRedisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置默认序列化器
        Jackson2JsonRedisSerializer<Employee> employeeSerializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        employeeRedisTemplate.setDefaultSerializer(employeeSerializer);
        return employeeRedisTemplate;
    }
}

测试下:

创建测试方法:


    @Autowired
    RedisTemplate redisTemplate;//操作k-v都是对象

    @Autowired
    RedisTemplate<Object, Employee> employeeRedisTemplate;


    /**
     * 功能描述: 测试保存对象
     */
    @Test
    public void test2() {
        Employee employee = employeeMapper.getEmpById(4);
        System.out.println("employee:" + employee.toString());
        //保存对象默认需要序列化,没有会现乱码.
        //redisTemplate.opsForValue().set("Spring-redisTemplate", employee);
        //1.将数据转成JSON保存
        //2.使用redisTemplate序列化规则;改变默认的序列化规则。
        employeeRedisTemplate.opsForValue().set("Spring-employeeRedisTemplate", employee);
    }

以上都测试成功!

相关文章

网友评论

    本文标题:SpringBoot整合Redis作为缓存(一)

    本文链接:https://www.haomeiwen.com/subject/aqmhoqtx.html