Redis缓存

2、 pom.xml 导入的包

        <!-- redis -->       
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency> 
        <!-- 缓存连接池-->
		<dependency>
		    <groupId>org.apache.commons</groupId>
		    <artifactId>commons-pool2</artifactId>
		</dependency>
		<!-- redis 存储 json序列化 -->
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		</dependency>
		<dependency>
		    <groupId>com.fasterxml.jackson.datatype</groupId>
		    <artifactId>jackson-datatype-jsr310</artifactId>
		</dependency>

3、配置文件设置


> **application.properties**

#Redis数据库索引(默认为0
spring.redis.database=0
#Redis服务器地址
spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis服务器连接密码(默认为空)
spring.redis.password=
#连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=10
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.pool.max-idle=8
#连接池中的最小空闲连接
spring.redis.pool.min-idle=0
#连接超时时间(毫秒)
spring.redis.timeout=0

############################################################################

> **application.yml**

#Spring配置
spring:
  #缓存管理器
  cache:
    type: redis
  #Redis配置
  redis:
    database: 0 #Redis数据库索引(默认为0)
    host: 127.0.0.1 #Redis服务器地址
    port: 6379 #Redis服务器连接端口
    password:  #Redis服务器连接密码(默认为空)
    jedis:
      pool:
        max-active: 8 #连接池最大连接数(使用负值表示没有限制)
        max-wait: -1s #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 8  #连接池中的最大空闲连接
        min-idle: 0 #连接池中的最小空闲连接
    lettuce:
      shutdown-timeout: 100ms #关闭超时时间,默认值100ms

4、启动类添加注解

import org.springframework.cache.annotation.EnableCaching;

@EnableCaching

5、Redis配置类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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 java.lang.reflect.Method;
 
/**
 * Redis配置类
 * lkm
 **/
@Configuration
public class RedisConfig extends CachingConfigurerSupport
{
    /**
     * 缓存对象集合中,缓存是以key-value形式保存的,
     * 当不指定缓存的key时,SpringBoot会使用keyGenerator生成Key。
     */
    @Bean
    public KeyGenerator keyGenerator()
    {
        return new KeyGenerator()
        {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder s = new StringBuilder();
                //类名+方法名
                s.append(target.getClass().getName());
                s.append(method.getName());
                for (Object obj : params) {
                    s.append(obj.toString());
                }
                return s.toString();
            }
        };
    }
 
    /**
     * 缓存管理器
     */
    @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory)
    {
        RedisCacheManager cacheManager = RedisCacheManager.create(connectionFactory);
        //设置缓存过期时间
        return cacheManager;
    }
 
    /**
     * 实例化RedisTemplate对象
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory)
    {
        StringRedisTemplate redisTemplate = new StringRedisTemplate(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);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

6、例子

public class RedisTemplateTests {

    @Resource
    private RedisTemplate redisTemplate;
    
    public void string1(){
    	//获取数据,直接赋值给实体
		实体 lkm = find();
		//向数据库中存储string类型的键值对, 过期时间5分钟
        redisTemplate.opsForValue().set("lkm", lkm, 5, TimeUnit.MINUTES);
	}

}

Spring 封装了 RedisTemplate 来操作 Redis,它支持所有的 Redis 原生的 API。在 RedisTemplate 中定义了对5种数据结构的操作方法。

opsForValue():操作字符串。
opsForList():操作列表。
opsForHash():操作哈希。
opsForSet():操作集合。
opsForZSet():操作有序集合。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傻猴儿

小编,多谢客官留下的赏钱。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值