springboot整合Redis

15 篇文章 0 订阅
7 篇文章 0 订阅

springboot整合Redis

1.x

  • pom
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
  • yml
#--------redis
#redis的数据库缩影,默认0
spring.redis.database=3
#服务器地址:
spring.redis.host=127.0.0.1
#服务器连接端口
spring.redis.port=6379
#连接密码,默认空
spring.redis.password=123456
#最大连接数(负值表示没有显示)
spring.redis.pool.max-active=1000
#最大阻塞等待时间(负值表示没有显示)
spring.redis.pool.max-wait=-1
#最大空闲连接
spring.redis.pool.max-idle=10
#最小空闲连接
spring.redis.pool.min-idle=2
#连接超时时间(ms)
spring.redis.timeout=0
  • redis配置:RedisConfig
package com.ucare.ucareschedule.utils;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
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.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * 缓存管理(注解用)
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * 生成key的策略
     *
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    /**
     * 管理缓存
     *
     * @param redisTemplate
     * @return
     */
    @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        // 设置缓存过期时间
        // rcm.setDefaultExpiration(60);//秒
        // 设置value的过期时间
        Map<String, Long> map = new HashMap<String, Long>();
        map.put("test", 60L);
        rcm.setExpires(map);
        return rcm;
    }
    /**
     * RedisTemplate配置
     * 
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
                Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);// 如果key是String
             // 需要配置一下StringSerializer,不然key会乱码
             // /XX/XX
        template.afterPropertiesSet();
        return template;
    }
}
  • 工具类
package com.ucare.ucareschedule.utils;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;/**
 * redicache 工具类
 * 
 */
@SuppressWarnings("unchecked")
@Component
public class RedisUtil {private static final Logger log = LoggerFactory.getLogger(RedisUtil.class);@SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;/**
     * 批量删除对应的value
     * 
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }/**
     * 批量删除key
     * 
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }/**
     * 删除对应的value
     * 
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }/**
     * 判断缓存中是否有对应的value
     * 
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }/**
     * redisTemplate.opsForValue();//操作字符串 redisTemplate.opsForHash();//操作hash
     * redisTemplate.opsForList();//操作list redisTemplate.opsForSet();//操作set
     * redisTemplate.opsForZSet();//操作有序set
     *//**
     * 读取缓存
     * 
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }/**
     * 写入缓存
     * 
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            log.error("redis Set Exception", e);
        }
        return result;
    }/**
     * 写入缓存 , +有效時間
     * 
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            log.error("redis Set with expireTime Exception", e);
        }
        return result;
    }/**
     * value是list类型 leftPush写入缓存
     */
    public boolean leftPush(final String key, Object value) {
        boolean result = false;
        try {
            ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
            listops.leftPush(key, value);
            result = true;
        } catch (Exception e) {
            log.error("leftPush",e);
        }
        return result;
    }/**
     * value是list类型 rightPush写入缓存
     */
    public boolean rightPush(final String key, Object value) {
        boolean result = false;
        try {
            ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
            listops.rightPush(key, value);
            result = true;
        } catch (Exception e) {
            log.error("rightPush",e);
        }
        return result;
    }/**
     * value是list类型 读取缓存
     * 
     * @param key
     * @return
     */
    public List<Object> getList(final String key, int start, int end) {
        List<Object> result = null;
        ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
        result = listops.range(key, start, end);
        return result;
    }/**
     * value是hash 写入缓存
     */
    public boolean setHash(final String key, Object HK, Object HV) {
        boolean result = false;
        try {
            HashOperations<Serializable, Object, Object> hashops = redisTemplate.opsForHash();
            hashops.put(key, HK, HV);
            result = true;
        } catch (Exception e) {
            log.error("setHash",e);
        }
        return result;
    }/**
     * value是hash 读取缓存
     * 
     * @param key
     * @return
     */
    public Object getHash(final String key, Object HK) {
        Object result = null;
        HashOperations<Serializable, Object, Object> hashops = redisTemplate.opsForHash();
        result = hashops.get(key, HK);
        return result;
    }/**
     * value是set 写入缓存
     */
    public boolean setSet(final String key, Object value) {
        boolean result = false;
        try {
            SetOperations<Serializable, Object> setops = redisTemplate.opsForSet();
            setops.add(key, value);
            result = true;
        } catch (Exception e) {
            log.error("setSet",e);
        }
        return result;
    }/**
     * value是set 读取缓存
     * 
     * @param key
     * @return
     */
    public Set<Object> getSet(final String key) {
        Set<Object> result = null;
        SetOperations<Serializable, Object> setops = redisTemplate.opsForSet();
        result = setops.members(key);
        return result;
    }/**
     * value是sorted set 写入缓存
     */
    public boolean sortedSet(final String key, Object value, double score) {
        boolean result = false;
        try {
            ZSetOperations<Serializable, Object> zsetops = redisTemplate.opsForZSet();
            zsetops.add(key, value, score);
            result = true;
        } catch (Exception e) {
            log.error("sortedSet",e);
        }
        return result;
    }/**
     * value是sorted set 读取缓存
     * 
     * @param key
     * @return
     */
    public Set<Object> getSortedSet(final String key, long start, long end) {
        Set<Object> result = null;
        ZSetOperations<Serializable, Object> zsetops = redisTemplate.opsForZSet();
        result = zsetops.range(key, start, end);
        return result;
    }}
  • 测试
    @Autowired
    private RedisUtil redisUtil;
    
    @Test
    public void  edit() {
        redisUtil.set("aa2", "1237eeeeezzh中89");
        System.out.println(redisUtil.get("aa2"));
    }

2.x

  • pom
<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  • yml
spring:
  redis:
    host: localhost
    port: 6379
    password: 123456
    jedis:
      pool:
        max-active: 1000
        max-wait: -1
        max-idle: 10
        min-idle: 2
    lettuce:
      pool:
        max-active: 1000
        max-wait: -1
        max-idle: 10
        min-idle: 2
        shutdown-timeout: 100ms
  cache:
    type: redis
  • 配置
package net.cc.schedule.redis.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;/**
 * Redis 配置类
 *
 * @author Leon
 * @version 2018/6/17 17:46
 */
@Configuration
// 必须加,使配置生效
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {/**
     * Logger
     */
    private static final Logger lg = LoggerFactory.getLogger(RedisConfig.class);
​
​
    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;@Bean
    @Override
    public KeyGenerator keyGenerator() {
        //  设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存
        // 使用:进行分割,可以很多显示出层级关系
        // 这里其实就是new了一个KeyGenerator对象,只是这是lambda表达式的写法,我感觉很好用,大家感兴趣可以去了解下
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(":");
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(":" + String.valueOf(obj));
            }
            String rsToUse = String.valueOf(sb);
            lg.info("自动生成Redis Key -> [{}]", rsToUse);
            return rsToUse;
        };
    }@Bean
    @Override
    public CacheManager cacheManager() {
        // 初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,我这里默认没有配置
        lg.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
                .RedisCacheManagerBuilder
                .fromConnectionFactory(jedisConnectionFactory);
        return builder.build();
    }@Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {
        //设置序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer); // key序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化
        redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }@Override
    @Bean
    public CacheErrorHandler errorHandler() {
        // 异常处理,当Redis发生异常时,打印日志,但是程序正常走
        lg.info("初始化 -> [{}]", "Redis CacheErrorHandler");
        CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
            @Override
            public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
                lg.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
            }@Override
            public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
                lg.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
            }@Override
            public void handleCacheEvictError(RuntimeException e, Cache cache, Object key)    {
                lg.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
            }@Override
            public void handleCacheClearError(RuntimeException e, Cache cache) {
                lg.error("Redis occur handleCacheClearError:", e);
            }
        };
        return cacheErrorHandler;
    }/**
     * 此内部类就是把yml的配置数据,进行读取,创建JedisConnectionFactory和JedisPool,以供外部类初始化缓存管理器使用
     * 不了解的同学可以去看@ConfigurationProperties和@Value的作用
     *
     */
    @ConfigurationProperties
    class DataJedisProperties{
        @Value("${spring.redis.host}")
        private  String host;
        @Value("${spring.redis.password}")
        private  String password;
        @Value("${spring.redis.port}")
        private  int port;
        @Value("${spring.redis.timeout}")
        private  int timeout;
        @Value("${spring.redis.jedis.pool.max-idle}")
        private int maxIdle;
        @Value("${spring.redis.jedis.pool.max-wait}")
        private long maxWaitMillis;@Bean
        JedisConnectionFactory jedisConnectionFactory() {
            lg.info("Create JedisConnectionFactory successful");
            JedisConnectionFactory factory = new JedisConnectionFactory();
            factory.setHostName(host);
            factory.setPort(port);
            factory.setTimeout(timeout);
            factory.setPassword(password);
            return factory;
        }
        @Bean
        public JedisPool redisPoolFactory() {
            lg.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port);
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxIdle(maxIdle);
            jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
​
            JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
            return jedisPool;
        }
    }}
  • 工具类
package net.cc.schedule.redis.impl;import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;import net.cc.schedule.redis.inter.RedisInter;/**
 * 
 * @desc redis实现类
 * @author zhangjing
 * @date 2018年12月4日 下午5:42:34
 */
@SuppressWarnings("unchecked")
@Component
public class RedisImpl implements RedisInter {private static final Logger log = LoggerFactory.getLogger(RedisImpl.class);@SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;/**
     * 批量删除对应的value
     * 
     * @param keys
     */
    @Override
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }/**
     * 批量删除key
     * 
     * @param pattern
     */
    @Override
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }/**
     * 删除对应的value
     * 
     * @param key
     */
    @Override
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }/**
     * 判断缓存中是否有对应的value
     * 
     * @param key
     * @return
     */
    @Override
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }/**
     * redisTemplate.opsForValue();//操作字符串 redisTemplate.opsForHash();//操作hash
     * redisTemplate.opsForList();//操作list redisTemplate.opsForSet();//操作set
     * redisTemplate.opsForZSet();//操作有序set
     *//**
     * 读取缓存
     * 
     * @param key
     * @return
     */
    @Override
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }/**
     * 写入缓存
     * 
     * @param key
     * @param value
     * @return
     */
    @Override
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            log.error("redis Set Exception", e);
        }
        return result;
    }/**
     * 写入缓存 , +有效時間
     * 
     * @param key
     * @param value
     * @return
     */
    @Override
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            log.error("redis Set with expireTime Exception", e);
        }
        return result;
    }/**
     * value是list类型 leftPush写入缓存
     */
    @Override
    public boolean leftPush(final String key, Object value) {
        boolean result = false;
        try {
            ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
            listops.leftPush(key, value);
            result = true;
        } catch (Exception e) {
            log.error("leftPush", e);
        }
        return result;
    }/**
     * value是list类型 rightPush写入缓存
     */
    @Override
    public boolean rightPush(final String key, Object value) {
        boolean result = false;
        try {
            ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
            listops.rightPush(key, value);
            result = true;
        } catch (Exception e) {
            log.error("rightPush", e);
        }
        return result;
    }/**
     * value是list类型 读取缓存
     * 
     * @param key
     * @return
     */
    @Override
    public List<Object> getList(final String key, int start, int end) {
        List<Object> result = null;
        ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
        result = listops.range(key, start, end);
        return result;
    }/**
     * value是hash 写入缓存
     */
    @Override
    public boolean setHash(final String key, Object HK, Object HV) {
        boolean result = false;
        try {
            HashOperations<Serializable, Object, Object> hashops = redisTemplate.opsForHash();
            hashops.put(key, HK, HV);
            result = true;
        } catch (Exception e) {
            log.error("setHash", e);
        }
        return result;
    }/**
     * value是hash 读取缓存
     * 
     * @param key
     * @return
     */
    @Override
    public Object getHash(final String key, Object HK) {
        Object result = null;
        HashOperations<Serializable, Object, Object> hashops = redisTemplate.opsForHash();
        result = hashops.get(key, HK);
        return result;
    }/**
     * value是set 写入缓存
     */
    @Override
    public boolean setSet(final String key, Object value) {
        boolean result = false;
        try {
            SetOperations<Serializable, Object> setops = redisTemplate.opsForSet();
            setops.add(key, value);
            result = true;
        } catch (Exception e) {
            log.error("setSet", e);
        }
        return result;
    }/**
     * value是set 读取缓存
     * 
     * @param key
     * @return
     */
    @Override
    public Set<Object> getSet(final String key) {
        Set<Object> result = null;
        SetOperations<Serializable, Object> setops = redisTemplate.opsForSet();
        result = setops.members(key);
        return result;
    }/**
     * value是sorted set 写入缓存
     */
    @Override
    public boolean sortedSet(final String key, Object value, double score) {
        boolean result = false;
        try {
            ZSetOperations<Serializable, Object> zsetops = redisTemplate.opsForZSet();
            zsetops.add(key, value, score);
            result = true;
        } catch (Exception e) {
            log.error("sortedSet", e);
        }
        return result;
    }/**
     * value是sorted set 读取缓存
     * 
     * @param key
     * @return
     */
    @Override
    public Set<Object> getSortedSet(final String key, long start, long end) {
        Set<Object> result = null;
        ZSetOperations<Serializable, Object> zsetops = redisTemplate.opsForZSet();
        result = zsetops.range(key, start, end);
        return result;
    }
}
  • 测试
    @Autowired
    private RedisImpl redisUtil;
    @Test
    public void  edit() {
        redisUtil.set("aa2", "1237eeeeezzh中89");
        System.out.println(redisUtil.get("aa2"));
    }
好的,下面是SpringBoot整合Redis的步骤: 1. 在pom.xml中引入Redis的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在application.properties或application.yml中配置Redis连接信息,例如: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.database=0 ``` 3. 创建RedisConfig类,配置RedisTemplate和StringRedisTemplate: ``` @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(redisConnectionFactory); return stringRedisTemplate; } } ``` 4. 在需要使用Redis的地方注入RedisTemplate或StringRedisTemplate,并使用相应方法操作Redis,例如: ``` @Autowired private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } ``` 以上就是SpringBoot整合Redis的基本步骤,希望能够帮到你。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值