微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SpringBoot整合Redis

SpringBoot整合Redis

1、引入pom依赖

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

        <!--        springboot集成redis所需common-pool2-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.0</version>
        </dependency>
        <!--        springboot集成redis所需common-pool2-->

2、yaml文件配置

spring:
  redis:
    host: #redis所在ip地址
    port: 6379
    password: #redis密码(需要用单引号括起来)
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 500
        min-idle: 0
    lettuce:
      shutdown-timeout: 30000

3、编写RedisConfig配置类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings("all")
    public Redistemplate<String, Object> redistemplate(RedisConnectionFactory factory) {
        Redistemplate<String, Object> template = new Redistemplate<String, Object>();
        template.setConnectionFactory(factory);
        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);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;

    }
}

4、编写RedisUtils

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Redistemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private Redistemplate<String, Object> redistemplate;

    /**
     * 写入缓存
     * @param key 键
     * @param value 值
     * @return  boolean
     */
    public boolean set(String key, Object value) {
        try {
             redistemplate.opsForValue().set(key, value);
             return true;
        } catch (Exception e) {
            e.printstacktrace();
            return false;
        }
    }

    /*
    获取缓存内的值
     */
    public Object get(Object key){
        return key == null ? null : redistemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time > 0 若 time <= 0 将设置无限期
     * @return true 成功 false 失败
     */
    public boolean setRedis(String key, Object value, long time) {
        try {
            if (time > 0) {
                redistemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printstacktrace();
            return false;
        }
    }
    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在    false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redistemplate.hasKey(key);
        } catch (Exception e) {
            e.printstacktrace();
            return false;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return redis
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }

        return redistemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return redis
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redistemplate.opsForValue().decrement(key, delta);
    }

    public boolean delete(String key){
        try {
            if(key == null){
                return false;
            }
            if(!redistemplate.hasKey(key)){
                return false;
            }
            return redistemplate.delete(key);
        } catch (Exception e) {
            e.printstacktrace();
            return false;
        }
    }
}

5、测试

@SpringBoottest
class ShoppingwallApplicationTests {
    @Autowired
    private RedisUtil redisUtil;

    @Test
    void test(){
        redisUtil.set("user","myValue");
        System.out.println(redisUtil.get("user"));  //myValue
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐