Spring Boot:(十三)redis缓存

开发前准备:

Spring Boot 项目;

redis 环境。


自定义redis配置

--------------------------------------------------------------------------------


1、pom.xml配置启动:

<profiles>

<profile>
<!-- 本地开发环境 -->
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
</profile>
<profile>
<!-- 生产环境 -->
<id>product</id>
<properties>
<profiles.active>product</profiles.active>
</properties>
</profile>

</profiles>


扫描二维码关注公众号,回复: 180812 查看本文章

2、pom.xml依赖:

<dependencies>
<!-- 使用log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 使用log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>


<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>


<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>

            <!--redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>


<!-- 使用log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

</dependencies>


3、*.properties文件配置:

#根据环境配置启动项目 ,指向pom.xml中的<profiles.active>标签

spring.profiles.active=@profiles.active@

spring.data.redis.repositories.enabled=false

spring.mvc.date-format=yyyy-MM-dd HH:mm:ss

spring.mvc.servlet.load-on-startup=1

#jackson
spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.generator.write-numbers-as-strings=true
spring.jackson.generator.ignore-unknown=true
spring.jackson.serialization.indent-output=true
spring.jackson.default-property-inclusion=non_null

#log
logging.path=/data/logs/sms/

logging.file=/data/logs/sms/sms.log

#自定义redis配置

sms.redis.host=58.87.89.22
sms.redis.port=12385

sms.redis.password=123456

sms.redis.database=0


4、读取application-*.properties配置文件如下图:



5、读取.properties配置文件的类:

自定义redis配置类


import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

@Configuration
@PropertySource("classpath: smsRedis-${spring.profiles.active}.properties") //指properties文件中的  spring.profiles.active
@EnableConfigurationProperties(SmsRedisProperties.class)
public class SmsRedisConfig {

    /**
     * Redis connection configuration.
     */
    @Configuration
    protected static class RedisConnectionConfiguration {

        private final SmsRedisProperties properties;

        public RedisConnectionConfiguration(SmsRedisProperties properties) throws UnknownHostException {
            this.properties = properties;
        }
        @Bean(name = "smsRedisTemplate")
        public RedisTemplate<Object, Object> redisTemplate() {
            RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
            template.setConnectionFactory(redisConnectionFactory());
            template.setKeySerializer(template.getStringSerializer());
            template.setValueSerializer(template.getStringSerializer());
            template.setHashKeySerializer(template.getStringSerializer());
            return template;
        }
        public JedisConnectionFactory redisConnectionFactory()
                 {
            JedisConnectionFactory factory = applyProperties(createJedisConnectionFactory());
            factory.afterPropertiesSet();
            return factory;
        }


        protected final JedisConnectionFactory applyProperties(
                JedisConnectionFactory factory) {
            configureConnection(factory);
            if (this.properties.isSsl()) {
                factory.setUseSsl(true);
            }
            factory.setDatabase(this.properties.getDatabase());
            if (this.properties.getTimeout() > 0) {
                factory.setTimeout(this.properties.getTimeout());
            }
            return factory;
        }


        private void configureConnection(JedisConnectionFactory factory) {
            if (StringUtils.hasText(this.properties.getUrl())) {
                configureConnectionFromUrl(factory);
            }
            else {
                factory.setHostName(this.properties.getHost());
                factory.setPort(this.properties.getPort());
                if (this.properties.getPassword() != null) {
                    factory.setPassword(this.properties.getPassword());
                }
            }
        }


        private void configureConnectionFromUrl(JedisConnectionFactory factory) {
            String url = this.properties.getUrl();
            if (url.startsWith("rediss://")) {
                factory.setUseSsl(true);
            }
            try {
                URI uri = new URI(url);
                factory.setHostName(uri.getHost());
                factory.setPort(uri.getPort());
                if (uri.getUserInfo() != null) {
                    String password = uri.getUserInfo();
                    int index = password.indexOf(":");
                    if (index >= 0) {
                        password = password.substring(index + 1);
                    }
                    factory.setPassword(password);
                }
            }
            catch (URISyntaxException ex) {
                throw new IllegalArgumentException("Malformed 'spring.redis.url' " + url,
                        ex);
            }
        }


        protected final RedisSentinelConfiguration getSentinelConfig() {
            SmsRedisProperties.Sentinel sentinelProperties = this.properties.getSentinel();
            if (sentinelProperties != null) {
                RedisSentinelConfiguration config = new RedisSentinelConfiguration();
                config.master(sentinelProperties.getMaster());
                config.setSentinels(createSentinels(sentinelProperties));
                return config;
            }
            return null;
        }


        /**
         * Create a {@link RedisClusterConfiguration} if necessary.
         * @return {@literal null} if no cluster settings are set.
         */
        protected final RedisClusterConfiguration getClusterConfiguration() {
            if (this.properties.getCluster() == null) {
                return null;
            }
            SmsRedisProperties.Cluster clusterProperties = this.properties.getCluster();
            RedisClusterConfiguration config = new RedisClusterConfiguration(
                    clusterProperties.getNodes());


            if (clusterProperties.getMaxRedirects() != null) {
                config.setMaxRedirects(clusterProperties.getMaxRedirects());
            }
            return config;
        }


        private List<RedisNode> createSentinels(SmsRedisProperties.Sentinel sentinel) {
            List<RedisNode> nodes = new ArrayList<RedisNode>();
            for (String node : StringUtils
                    .commaDelimitedListToStringArray(sentinel.getNodes())) {
                try {
                    String[] parts = StringUtils.split(node, ":");
                    Assert.state(parts.length == 2, "Must be defined as 'host:port'");
                    nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
                }
                catch (RuntimeException ex) {
                    throw new IllegalStateException(
                            "Invalid redis sentinel " + "property '" + node + "'", ex);
                }
            }
            return nodes;
        }


        private JedisConnectionFactory createJedisConnectionFactory() {
            JedisPoolConfig poolConfig = this.properties.getPool() != null
                    ? jedisPoolConfig() : new JedisPoolConfig();

            if (getSentinelConfig() != null) {
                return new JedisConnectionFactory(getSentinelConfig(), poolConfig);
            }
            if (getClusterConfiguration() != null) {
                return new JedisConnectionFactory(getClusterConfiguration(), poolConfig);
            }
            return new JedisConnectionFactory(poolConfig);
        }


        private JedisPoolConfig jedisPoolConfig() {
            JedisPoolConfig config = new JedisPoolConfig();
            SmsRedisProperties.Pool props = this.properties.getPool();
            config.setMaxTotal(props.getMaxActive());
            config.setMaxIdle(props.getMaxIdle());
            config.setMinIdle(props.getMinIdle());
            config.setMaxWaitMillis(props.getMaxWait());
            return config;
        }

    }
}


配置文件属性类:

import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;

@ConfigurationProperties(prefix = "sms.redis")
public class SmsRedisProperties {

/**
* Database index used by the connection factory.
*/
private int database = 0;

/**
* Redis url, which will overrule host, port and password if set.
*/
private String url;

/**
* Redis server host.
*/
private String host = "localhost";

/**
* Login password of the redis server.
*/
private String password;

/**
* Redis server port.
*/
private int port = 6379;

/**
* Enable SSL.
*/
private boolean ssl;

/**
* Connection timeout in milliseconds.
*/
private int timeout;

private SmsRedisProperties.Pool pool;

private SmsRedisProperties.Sentinel sentinel;

private SmsRedisProperties.Cluster cluster;

public int getDatabase() {
return this.database;
}

public void setDatabase(int database) {
this.database = database;
}

public String getUrl() {
return this.url;
}

public void setUrl(String url) {
this.url = url;
}

public String getHost() {
return this.host;
}

public void setHost(String host) {
this.host = host;
}

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

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

public int getPort() {
return this.port;
}

public void setPort(int port) {
this.port = port;
}

public boolean isSsl() {
return this.ssl;
}

public void setSsl(boolean ssl) {
this.ssl = ssl;
}

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

public int getTimeout() {
return this.timeout;
}

public SmsRedisProperties.Sentinel getSentinel() {
return this.sentinel;
}

public void setSentinel(SmsRedisProperties.Sentinel sentinel) {
this.sentinel = sentinel;
}

public SmsRedisProperties.Pool getPool() {
return this.pool;
}

public void setPool(SmsRedisProperties.Pool pool) {
this.pool = pool;
}

public SmsRedisProperties.Cluster getCluster() {
return this.cluster;
}

public void setCluster(SmsRedisProperties.Cluster cluster) {
this.cluster = cluster;
}


/**
* Pool properties.
*/
public static class Pool {

/**
* Max number of "idle" connections in the pool. Use a negative value to indicate
* an unlimited number of idle connections.
*/
private int maxIdle = 8;

/**
* Target for the minimum number of idle connections to maintain in the pool. This
* setting only has an effect if it is positive.
*/
private int minIdle = 0;

/**
* Max number of connections that can be allocated by the pool at a given time.
* Use a negative value for no limit.
*/
private int maxActive = 8;

/**
* Maximum amount of time (in milliseconds) a connection allocation should block
* before throwing an exception when the pool is exhausted. Use a negative value
* to block indefinitely.
*/
private int maxWait = -1;

public int getMaxIdle() {
return this.maxIdle;
}

public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}

public int getMinIdle() {
return this.minIdle;
}

public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}

public int getMaxActive() {
return this.maxActive;
}

public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}

public int getMaxWait() {
return this.maxWait;
}

public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}

}


/**
* Cluster properties.
*/
public static class Cluster {

/**
* Comma-separated list of "host:port" pairs to bootstrap from. This represents an
* "initial" list of cluster nodes and is required to have at least one entry.
*/
private List<String> nodes;

/**
* Maximum number of redirects to follow when executing commands across the
* cluster.
*/
private Integer maxRedirects;

public List<String> getNodes() {
return this.nodes;
}

public void setNodes(List<String> nodes) {
this.nodes = nodes;
}

public Integer getMaxRedirects() {
return this.maxRedirects;
}

public void setMaxRedirects(Integer maxRedirects) {
this.maxRedirects = maxRedirects;
}

}


/**
* Redis sentinel properties.
*/
public static class Sentinel {

/**
* Name of Redis server.
*/
private String master;

/**
* Comma-separated list of host:port pairs.
*/
private String nodes;

public String getMaster() {
return this.master;
}

public void setMaster(String master) {
this.master = master;
}

public String getNodes() {
return this.nodes;
}

public void setNodes(String nodes) {
this.nodes = nodes;
}

}
}


6、调用自定义redis的service接口

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SmsRedisService {
private Logger logger = LoggerFactory.getLogger(SmsRedisService .class);

@Resource(name = "smsRedisTemplate")
private RedisTemplate<String, String> smsRedisTemplate;

/**
* 获取redis缓存的短信验证码 

* @param key
* @return 时间: 2018年2月27日 下午3:10:02 描述:
*/
public String get(String key) {
return smsRedisTemplate.opsForValue().get(key);
}

/**
* 重置redis缓存的短信验证码,并设置过期时间 

* @param key
* @param value
* @param time
* @param type
*            时间: 2018年2月27日 下午3:10:30 描述:
*/
public void set(String key, String value, long time, TimeUnit type) {
smsRedisTemplate.opsForValue().set(key, value, time, type);
}

/**
* 清除redis缓存的短信验证码 

* @param key
*            时间: 2018年2月27日 下午3:13:40 描述:
*/
public void delete(String key) {
smsRedisTemplate.delete(key);
}

}


至此,配置使用 redis的 已经可以 在controller 中使用了。

后续介绍 使用spring boot发送短信。

谢谢大家。





猜你喜欢

转载自blog.csdn.net/y_h_d/article/details/80090966