Redis--SpringBoot 整合 Redis(包含工具类)
 作者:Java学术趴
- 2022 年 10 月 03 日 北京
- 本文字数:2995 字 - 阅读完需:约 10 分钟 

👨🎓作者:Java 学术趴
💌公众号:Java 学术趴
🚫特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系小编授权。
🙏版权声明:文章里的部分文字或者图片来自于互联网以及百度百科,如有侵权请尽快联系小编。微信搜索公众号 Java 学术趴联系小编。
☠️每日毒鸡汤:一件事你犹豫去不去做,那就是该立即动身做的。
第一步:引入 SpringBoot 中关于 Redis 的依赖
        <!-- redis依赖 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency>        <!-- Redis连接池配置 -->        <dependency>            <groupId>org.apache.commons</groupId>            <artifactId>commons-pool2</artifactId>        </dependency>
复制代码
 第二步:在 application.yml 文件中进行 Redis 的配置
 # redis 配置  redis:    # Redis地址    host: redis63701.yyyw.gyyxdl.cn    # Redis端口    port: 63701    # Redis密码    password: 0tIxKtzsf2    # Redis 指定库    database: 0    # Redis 链接超时时间(毫秒)    timeout: 180000    # Redis 线程池配置    lettuce:      pool:        # 连接池最大链接数(负数代表没有限制)        max-active: 32        # 最大阻塞时间(负数代表没有限制)        max-wait: 300ms        # 最大空闲链接        max-idle: 16        # 最小空闲链接        min-idle: 8
复制代码
 第三步:编写 Redis 的配置类
package com.sea.whale.config;/** * @author : YunboCheng * @date : 18:15 2022-08-28 */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.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheConfiguration;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.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;/** * @description: Redis配置 * @author: chengyunbo@gyyx.cn * @time: 18:15 */@EnableCaching //开启缓存@Configuration  //配置类public class RedisConfig extends CachingConfigurerSupport {    @Bean    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {        RedisTemplate<String, Object> template = new RedisTemplate<>();        RedisSerializer<String> redisSerializer = new StringRedisSerializer();        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);        ObjectMapper om = new ObjectMapper();        //om.setSerializationInclusion(JsonInclude.Include.NON_NULL);        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);        jackson2JsonRedisSerializer.setObjectMapper(om);        template.setConnectionFactory(factory);        //key序列化方式        template.setKeySerializer(redisSerializer);        //value序列化        template.setValueSerializer(jackson2JsonRedisSerializer);        //value hashmap序列化        template.setHashValueSerializer(jackson2JsonRedisSerializer);        return template;    }    @Bean    public CacheManager cacheManager(RedisConnectionFactory factory) {        RedisSerializer<String> redisSerializer = new StringRedisSerializer();        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);        //解决查询缓存转换异常的问题        ObjectMapper om = new ObjectMapper();        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);        //om.setSerializationInclusion(JsonInclude.Include.NON_NULL);        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);        jackson2JsonRedisSerializer.setObjectMapper(om);        // 配置序列化(解决乱码的问题),过期时间600秒        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()                .entryTtl(Duration.ofDays(1))                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))                .disableCachingNullValues();        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)                .cacheDefaults(config)                .build();        return cacheManager;    }}
复制代码
 第四步:编写一个测试类,测试是否可以访问 Redis
package com.sea.whale.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * <p> *  前端控制器 * </p> * * @author Whale * @since 2022-08-24 21:20:00 */@RestController@RequestMapping("/whaleFall")public class WhaleFallController {    @Autowired    private RedisTemplate<String, String> redisTemplate;    @GetMapping("testRedis")    public String testRedis() {        // 设置值到 Redis 中        redisTemplate.opsForValue().set("name","jack");        // 从 Redis 中获取值        String name = redisTemplate.opsForValue().get("name");        System.out.println(name);        return name;    }}
复制代码
 第五步:访问这个路径,查看是否可以获取到指定 key 对应的 value 值
 
 划线
评论
复制
发布于: 刚刚阅读数: 4

Java学术趴
关注
还未添加个人签名 2022.07.02 加入
还未添加个人简介










 
    
评论