自定义redis-spring-boot-starter 自动化配置。

工程架构

在这里插入图片描述

starter为通用的组件

建立一个module 工程 xlc-commns
里面进行自定义starter,这里我就写一个redis-starter 作为例子

package cloud.redis;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author cunfeng
 * @create 2021-05-06 10:23
 */

@ConfigurationProperties(prefix = "myredis") //自定义yml格式 随便起名
public class MyRedisProperties {
    /**
     * ip地址
     */
    private String host;
    /**
     * 端口号
     */
    private  int  port;

    /**
     * 密码
     */
    private String password;
    /**
     * 接池中总连接的最大数量
     */
    private int   maxActive;
    /**
     *  连接池中空闲连接的最大数量
     */
    private int   maxIdle;
    /**
     * 最大建立连接等待时间
     */
    private  int  maxWait;
    /**
     * 超时时间
     */
    private  int timeout;
    /**
     *    第几个数据库
     */
    private int database;

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
    public int getMaxActive() {
        return maxActive;
    }
    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }
    public int getMaxIdle() {
        return maxIdle;
    }
    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }
    public int getMaxWait() {
        return maxWait;
    }
    public void setMaxWait(int maxWait) {
        this.maxWait = maxWait;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public int getDatabase() {
        return database;
    }

    public void setDatabase(int database) {
        this.database = database;
    }
}
package cloud.redis;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * 利用jedis 进行连接redis
 * @author cunfeng
 * @create 2021-05-06 10:33
 */
@Configuration
@EnableConfigurationProperties(MyRedisProperties.class)//开启属性注入,通过@autowired注入
@ConditionalOnClass(RedisClient.class)//判断这个类是否在classpath中存在
public class MyRedisAutoConfigulation {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MyRedisProperties prop;

    @Bean(name="jedisPool")
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        //连接池中空闲连接的最大数量
        config.setMaxIdle(prop.getMaxIdle());
        // 接池中总连接的最大数量
        config.setMaxTotal(prop.getMaxActive());
        //最大建立连接等待时间
        config.setMaxWaitMillis(prop.getMaxWait());
        //第几个数据库
        int database = prop.getDatabase();
        //密码
        String password = prop.getPassword();
        int timeout = prop.getTimeout();
        if(StringUtils.isNotBlank(password)){
            logger.info("初始化redis连接池完毕--------------");
            return new JedisPool(config, prop.getHost(), prop.getPort(),timeout,password,database);
        }else {
            logger.info("初始化redis连接池完毕--------------");
            return new JedisPool(config, prop.getHost(), prop.getPort(),timeout,null,database);
        }

    }

    @Bean
    @ConditionalOnMissingBean(RedisClient.class)//容器中如果没有RedisClient这个类,那么自动配置这个RedisClient
    public RedisClient redisClient(@Qualifier("jedisPool")JedisPool pool) {
        RedisClient redisClient = new RedisClient();
        redisClient.setJedisPool(pool);
        return redisClient;
    }

}
package cloud.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;

/**
 * 常用的redis方法
 * @author cunfeng
 * @create 2021-05-06 10:53
 */
public class RedisClient {

    private Logger log = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private JedisPool jedisPool;


    /**
     * 处理jedis请求
     * @param f 处理逻辑,通过lambda行为参数化
     * @return 处理结果
     */
    private Object excuteByJedis(Function<Jedis, Object> f) {
        Jedis jedis = null;
        try{
            jedis= jedisPool.getResource();
            return f.apply(jedis);
        } catch (Exception e) {
            e.printStackTrace();
            if(jedis != null ) {
                jedisPool.close();
            }
            log.error("redis资源池发生错误:"+e.getMessage());
            return null;
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }

    public Map<String, Object> getKeysSize() {
        long dbSize = (long) this.excuteByJedis(
                j -> {
                    Client client = j.getClient();
                    client.dbSize();
                    return client.getIntegerReply();
                }
        );
        Map<String, Object> map = new HashMap<>();
        map.put("create_time", System.currentTimeMillis());
        map.put("dbSize", dbSize);
        return map;
    }

    public Map<String, Object> getMemoryInfo() {
        String info = (String) this.excuteByJedis(
                j -> {
                    Client client = j.getClient();
                    client.info();
                    return client.getBulkReply();
                }
        );
        String[] strs = Objects.requireNonNull(info).split("\n");
        Map<String, Object> map = null;
        for (String s : strs) {
            String[] detail = s.split(":");
            if ("used_memory".equals(detail[0])) {
                map = new HashMap<>();
                map.put("used_memory", detail[1].substring(0, detail[1].length() - 1));
                map.put("create_time", System.currentTimeMillis());
                break;
            }
        }
        return map;
    }


    public Set<String> getKeys(String pattern) {
        return (Set<String>) this.excuteByJedis(j -> j.keys(pattern));
    }


    public String get(String key) {
        return (String) this.excuteByJedis(j -> j.get(key));
    }


    public String set(String key, String value) {
        return (String) this.excuteByJedis(j -> j.set(key, value));
    }


    public Long del(String... key) {
        return (Long) this.excuteByJedis(j -> j.del(key));
    }


    public Boolean exists(String key) {
        return (Boolean) this.excuteByJedis(j -> j.exists(key));
    }


    public Long pttl(String key) {
        return (Long) this.excuteByJedis(j -> j.pttl(key));
    }


    public Long pexpire(String key, Long milliseconds) {
        return (Long) this.excuteByJedis(j -> j.pexpire(key, milliseconds));
    }

    public String haSet(String key, Map<String, String> map) {
        return (String) this.excuteByJedis(j -> j.hmset(key, map));
    }

    public Map<String,String> hmGetAll(String key) {
        return  (Map<String, String>) this.excuteByJedis(j -> j.hgetAll(key));
    }

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

}  

最关键的配置

在这里插入图片描述

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cloud.redis.MyRedisAutoConfigulation

web工程继承redis-starter

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>redis-starter</artifactId>
        <groupId>org.xlc</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>xlc-admin</artifactId>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <!--自定义yml提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.2.6.RELEASE</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.xlc</groupId>
            <artifactId>redis-spring-boot-starter</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <finalName>wangxiao</finalName>
    </build>

</project>

测试demo

package cloud.test;
import cloud.redis.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @MethodName: 测试类
 * @Author: cunfeng
 * @Date: 2021年05月05日 16:56
 **/
@RestController

public class test {

    @Autowired
    private RedisClient redisClient;


    @RequestMapping("/set")
    public String set(String key, String value) {
        redisClient.set(key, value);
        return "success";
    }

    @RequestMapping("/get")
    public String get(String key){
        return redisClient.get(key);
    }

}

server:
  port: 2222
  servlet:
    context-path: /
myredis:                  #自定义yml
  host: 192.168.2.204
  port: 6379
  password:
  min-idle: 8         #空闲 最小链接数
  max-idle: 500       #空闲 最大链接数
  max-active: 2000    #最大链接数
  max-wait: 10000     #最大建立连接等待时间
  timeout: 30000      #超时时间
  database: 1          #第几个数据库

gitee 项目地址

https://gitee.com/YuXuanPer/redis-starter

测试案列不易,多多支持

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
shiro-redis-spring-boot-starter是一个用于集成Apache Shiro和Redis的Spring Boot Starter项目。Apache Shiro是一个强大而灵活的Java安全框架,用于身份验证、授权和会话管理等安全功能。而Redis是一个高性能的内存数据库,其具有快速的数据存取能力和持久化支持。 shiro-redis-spring-boot-starter提供了一种简化和快速集成Shiro和Redis的方式,使得在Spring Boot应用中实现安全功能变得更加容易。通过使用该Starter,我们可以方便地将Shiro的会话管理功能存储到Redis中,从而支持分布式环境下的会话共享和管理。 使用shiro-redis-spring-boot-starter可以带来以下好处: 1. 分布式环境的会话共享:通过将Shiro的会话数据存储到Redis中,不同的应用节点可以共享同一个会话,从而实现分布式环境下的会话管理和跨节点的身份验证和授权。 2. 高可用性和性能:Redis作为一个高性能的内存数据库,具有出色的数据读写能力和持久化支持,可以提供可靠的会话存储和高性能的数据访问能力。 3. 简化配置和集成:shiro-redis-spring-boot-starter提供了封装好的配置和集成方式,减少了我们自己实现集成的复杂性和工作量。 总结来说,shiro-redis-spring-boot-starter为我们提供了一种简化和快速集成Shiro和Redis的方式,使得在Spring Boot应用中实现安全功能变得更加容易和高效。通过它,我们可以实现分布式环境下的会话共享和管理,提供高可用性和性能的数据存取能力,同时简化了配置和集成的复杂性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值