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

 

posted @   雷雨客  阅读(499)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示