Springboot自动装配 - redis和redission

Springboot自动装配 - redis和redission

    • [1. 自动装配](#1. 自动装配)
    • [2. redis自动装配示例](#2. redis自动装配示例)

1. 自动装配

Spring Boot的核心理念是简化Spring应用的搭建和开发过程,提出了约定大于配置和自动装配的思想 。开发Spring项目通常要配置xml文件,当项目变得复杂的时候,xml的配置文件也将变得极其复杂。为了解决这个问题,我们将一些常用的通用的配置先配置好,要用的时候直接装上去,不用的时候卸下来,这些就是Spring Boot框架在Spring框架的基础上要解决的问题。

Spring Boot的自动装配得益于有一批优秀的程序员写好了很多场景启动器(starter),比如web场景下的spring-boot-starter-web,cache场景下的spring-boot-starter-cache等。

2. redis自动装配示例

step 1: 引入依赖

java 复制代码
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

step 2: 配置文件中增加redis配置

java 复制代码
spring:
  redis:
    host: 127.0.0.1
    port: 6379

step 3: 注入redisTemplate

java 复制代码
1. 可以直接在要使用的地方注入
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
 2. 也可以使用构造方法注入
 public class useCacheManager{
	    private final RedisTemplate<Object,Object> redisTemplate;
	    private final String caffeineSpec;
			public useCacheManager(RedisTemplate<Object,Object> redisTemplate){
				this.redisTemplate = redisTemplate;
				this.caffeineSpec = "";
			}
	}

Boot 默认自动配置的 RedisTemplate的泛型类型是 <Object, Object>。而您在代码中注入时,通常声明的是更具体的类型,例如 RedisTemplate<String, Object>。由于 @Autowired默认按类型注入,它会寻找完全匹配的泛型类型,因此找不到就会报错

step 4(可选): 使用更具体的类型,需要增加自定义配置

java 复制代码
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.StringRedisSerializer;

@Configuration
public class RedisConfig {
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        
        // 建议设置key的序列化器,避免在Redis中看到乱码
        template.setKeySerializer(new StringRedisSerializer());
        // 可以根据需要设置value的序列化器,例如Jackson2JsonRedisSerializer
        // template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        
        return template;
    }
}

step 5: 使用

java 复制代码
redisTemplate.opsForValue().set(key, value);
redisTemplate.opsForValue().get(key);
相关推荐
AI大模型-小华9 小时前
Codex 三方充值快速入门指南
java·前端·数据库·chatgpt·ai编程·codex·chatgpt pro
Mark_ZP10 小时前
【锁1】Synchronized vs ReentrantLock区别
java
立心者010 小时前
SpringBoot中使用TOTP实现MFA(多因素认证)
java·spring boot·后端
枕星而眠10 小时前
C++ STL Map容器完全指南:从有序红黑树到无序哈希表
java·开发语言
bbq粉刷匠11 小时前
HashMap 底层原理深度拆解(二):putVal 完整链路解析(懒加载 · 链表遍历 · 尾插法)
java·开发语言·哈希算法
Sam_Deep_Thinking12 小时前
一个靠谱的C端网关服务应该包含什么内容
java·程序员·系统架构
Valora12 小时前
简单学会redis
redis
杨运交12 小时前
[055][调度模块]Spring动态任务调度框架的设计与实现
java·后端·spring
白狐_79812 小时前
408 数据结构算法题 01:线性表暴力求解保分指南
java·数据结构·算法
流云鹤13 小时前
03Java学习day(3)
java·学习