标签:primary   remove   warning   final   art   template   ati   conf   war   
如何在spring-boot中使用Redis工具类
修改pom.xml文件
新增spring-boot-starter-data-redis配置
        org.springframework.boot
            spring-boot-starter-data-redis
        
 
修改application.yml
新增Redis配置
server:
  port: 6660
  redis:
    host: 127.0.0.1
    port: 6379
    password:
 
新增config目录
RedisConfig.java文件
package com.example.redisdemo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
 * @author komiles@163.com
 * @date 2020-05-22 14:40
 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    /**
     * 实例化redisTempate对象
     * primary 在autowired时,优先选择我注册的bean
     * 因为在redis 框架中有注册一个StringRedisTemplate,避免注入冲突
     * @return
     */
    @Bean
    @Primary
    public RedisTemplate RedisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate();
        initRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }
    /**
     * 设置数据存入Redis的序列化方式
     * @param redisTemplate
     * @param factory
     */
    private void initRedisTemplate(RedisTemplate redisTemplate, RedisConnectionFactory factory) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
    }
}
 
新增RedisUtil.java文件
package com.example.redisdemo.util;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
/**
 * @author komiles@163.com
 * @date 2020-05-22 15:31
 */
@Component
public final class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;
    // =============================common============================
    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
    /**
     * 判断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 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }
    // ============================String=============================
    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(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;
        }
    }
    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    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
     */
    public long decr(String key, long delta) {
        if (delta 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }
    // ================================Map=================================
    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map
 
新增Test2Controller.java
package com.example.redisdemo.controller;
import com.example.redisdemo.dao.Person;
import com.example.redisdemo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author komiles@163.com
 * @date 2020-05-22 15:13
 */
@RestController
@RequestMapping("/test2")
public class Test2Controller {
    static final String USER_LIST_HASH_KEY = "student_list_0522_02";
    @Autowired
    RedisUtil redisUtil;
    @GetMapping("/set")
    public String setStr(@Param("key") String key, @Param("value") String value){
        redisUtil.set(key,value);
        return key;
    }
    @GetMapping("/get")
    public String setStr(@Param("key") String key){
        return redisUtil.get(key).toString();
    }
    @GetMapping("/hashSet")
    public String setHash(){
        Person person = new Person();
        person.setId("1").setName("张三");
        redisUtil.hset(USER_LIST_HASH_KEY,person.getId(),person);
        return "OK";
    }
    @GetMapping("/hashGet")
    public Object getHash(){
        Person person = new Person();
        person.setId("1").setName("张三");
        return redisUtil.hget(USER_LIST_HASH_KEY,"1");
    }
}
 
新增实体类 Person.java
用来测试
package com.example.redisdemo.dao;
import java.io.Serializable;
import lombok.Data;
import lombok.experimental.Accessors;
/**
 * @author komiles@163.com
 * @date 2020-05-22 15:11
 */
@Data
@Accessors(chain = true)
public class Person implements Serializable {
    private static final Long serialVersionUID = 99999L;
    private String id;
    private String name;
}
 
调用controller.java
- http://localhost:6660/test2/set?key=user_name&value=kongming
 
项目demo地址
- https://github.com/KoMiles/spring-example/tree/master/redis-demo
 
【spring-boot】配置Redis工具类
标签:primary   remove   warning   final   art   template   ati   conf   war   
原文地址:https://www.cnblogs.com/wangkongming/p/12938709.html