SpringBoot中自定义starter-redis
SpringBoot能快速开发之一是因为只要引入某个starter就可获取其服务。现自己实现starter-redis,并且总结步骤。
一、创建SpringBoot工程starter-redis
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2、读取属性类
@ConfigurationProperties(prefix="redis") public class RedisProperties { private String host; private Integer port; private String password; ... get set 方法... }
3、自动配置bean类
@Configuration @ConditionalOnClass(Jedis.class) @EnableConfigurationProperties(RedisProperties.class) public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean public Jedis jedis(RedisProperties redisProperties) { Jedis jedis = new Jedis(redisProperties.getHost(),redisProperties.getPort()); jedis.auth(redisProperties.getPassword()); return jedis; } }
4、导入配置注解
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(RedisAutoConfiguration.class) public @interface EnableRedis { }
二、创建SpringBoot测试工程starter-redis-app
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.leiyuke</groupId>
<artifactId>starter-redis</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
2、配置文件增加参数
redis.host=127.0.0.1 redis.port=6379 redis.password=123456
3、启动类添加Enable测试
@SpringBootApplication @EnableRedis public class App { public static void main(String[] args) { ConfigurableApplicationContext context= SpringApplication.run(App.class, args); Jedis jedis = context.getBean(Jedis.class); jedis.set("testKey","testValue"); System.out.println(jedis.get("testKey")); context.close(); } }
说明:
starter-redis中也可以不创建注解EnableRedis,只需在任一工程的resources/META-INF/spring.factories中添加如下配置即可
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.leiyuke.starter.redis.RedisAutoConfiguration
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步