Spring整合Redis

Posted CaoPengCheng&

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring整合Redis相关的知识,希望对你有一定的参考价值。

Spring整合Redis

一,maven导入依赖

 <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.6.2.RELEASE</version>
</dependency>

二,Spring整合

(1)SpringBoot

spring:
  # 资源信息
  messages:
    # 国际化资源文件路径
    basename: i18n/messages
  profiles: 
    active: druid
  # 文件上传
  servlet:
     multipart:
       # 单个文件大小
       max-file-size:  10MB
       # 设置总上传的文件大小
       max-request-size:  20MB
  # 服务模块
  devtools:
    restart:
      # 热部署开关
      enabled: true
  # redis 配置
  redis:
    # 地址
    host: localhost
    # 端口,默认为6379
    port: 6379
    # 数据库索引
    database: 0
    # 密码
    password: 
    # 连接超时时间
    timeout: 10s
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池的最大数据库连接数
        max-active: 8
        # #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms

(2)Spring

	# 服务器ip
	redis.hostname = 127.0.0.1
	
	# redis数据库端口
	redis.port = 6379
	
	# 使用的数据库(共有16个数据库0~15)
	redis.database = 2
	
	# 控制一个pool可分配多少个jedis示例
	redis.pool.maxActive = 50
	
	# 控制一个pool最多有多少个状态为idle的jedis实例
	redis.pool.maxIdle = 300
	
	# 最大等待连接时间(单位毫秒)
	redis.pool.maxTotal = 600
	
	# redis密码一般不设置密码,设了重启服务也会没有
	redis.pass =
   <!-- 载入配置文件 -->
    <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/>

    <!-- 配置JedisPoolConfig示例 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="$redis.pool.maxIdle"/>
        <property name="maxTotal" value="$redis.pool.maxTotal"/>
    </bean>

    <!-- 配置JedisConnectionFactory -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="$redis.hostname"/>
        <property name="port" value="$redis.port"/>
        <property name="password" value="$redis.pass"/>
        <property name="database" value="$redis.database"/>
        <property name="poolConfig" ref="poolConfig"/>
        <property name="usePool" value="true"/>
    </bean>

    <!-- 配置RedisTemplate-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
        <property name="defaultSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>
        <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="hashValueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>
    </bean>

三,使用RedisCacheUtil工具类

package com.hcepms.base.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * redis 工具类
 *
 * @author CaoPengCheng
 * @date 2022/8/5 18:45
 */
@SuppressWarnings(value = "unchecked", "rawtypes")
@Component
public class RedisCacheUtil 

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     * @return
     * @author .com
     * @date 2022/8/5 18:51
     */
    public void setCacheObject(String key, Object value) 
        redisTemplate.opsForValue().set(key, value);
    

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     * @return
     * @author .com
     * @date 2022/8/5 18:51
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) 
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    

    /**
     * 设置有效时间 true=设置成功;false=设置失败
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @return @link boolean
     * @author .com
     * @date 2022/8/5 18:51
     */
    public boolean expire(final String key, final long timeout) 
        return expire(key, timeout, TimeUnit.SECONDS);
    

    /**
     * 设置有效时间 true=设置成功;false=设置失败
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return @link boolean
     * @author .com
     * @date 2022/8/5 18:50
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) 
        return redisTemplate.expire(key, timeout, unit);
    

    /**
     * 获得缓存的基本对象
     *
     * @param key 缓存键值
     * @return @link T  缓存键值对应的数据
     * @author .com
     * @date 2022/8/5 18:50
     */
    public <T> T getCacheObject(final String key) 
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    

    /**
     * 删除单个对象
     *
     * @param key
     * @return @link boolean
     * @author .com
     * @date 2022/8/5 18:49
     */
    public void deleteObject(final String key) 
        redisTemplate.delete(key);
    

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return @link long
     * @author .com
     * @date 2022/8/5 18:49
     */
    public void deleteObject(final Collection collection) 
        redisTemplate.delete(collection);
    

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return @link long 缓存的对象
     * @author .com
     * @date 2022/8/5 18:49
     */
    public <T> long setCacheList(final String key, final List<T> dataList) 
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return @link List<T> 缓存键值对应的数据
     * @author .com
     * @date 2022/8/5 18:48
     */
    public <T> List<T> getCacheList(final String key) 
        return redisTemplate.opsForList().range(key, 0, -1);
    

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return @link BoundSetOperations< String,T> 缓存数据的对象
     * @author .com
     * @date 2022/8/5 18:48
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) 
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) 
            setOperation.add(it.next());
        
        return setOperation;
    

    /**
     * 获得缓存的set
     *
     * @param key
     * @return @link Set<T>
     * @author .com
     * @date 2022/8/5 18:47
     */
    public <T> Set<T> getCacheSet(final String key) 
        return redisTemplate.opsForSet().members(key);
    

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     * @return
     * @author .com
     * @date 2022/8/5 18:47
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) 
        if (dataMap != null) 
            redisTemplate.opsForHash().putAll(key, dataMap);
        
    

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return @link Map< String,T>
     * @author .com
     * @date 2022/8/5 18:47
     */
    public <T> Map<String, T> getCacheMap(final String key) 
        return redisTemplate.opsForHash().entries(key);
    

    /**
     * 往Hash中存入数据
     *
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     * @return
     * @author .com
     * @date 2022/8/5 18:45
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) 
        redisTemplate.opsForHash().put(key, hKey, value);
    

    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return @link T
     * @author .com
     * @date 2022/8/5 18:45
     */
    public <T> T getCacheMapValue(final String key, final String hKey) 
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    

    /**
     * 删除Hash中的数据
     *
     * @param key
     * @param hkey
     * @return
     * @author .com
     * @date 2022/8/5 18:44
     */
    public void delCacheMapValue(final String key, final String hkey) 
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);
    

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return @link List<T>
     * @author .com
     * @date 2022/8/5 18:44
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) 
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return @link Collection< String>  对象列表
     * @author .com
     * @date 2022/8/5 18:45
     */
    public Collection<String> keys(final String pattern) 
        return redisTemplate.keys(pattern);
    


以上是关于Spring整合Redis的主要内容,如果未能解决你的问题,请参考以下文章

spring整合redis后怎么更改db

Spring Boot如何整合Redis

Spring Boot如何整合Redis

redis与spring整合实例

jedis的使用,spring整合redis,springboot整合redis

spring整合jedis怎么指定密码