spring-data-redis的测试程序

启动程序:

package net.highersoft;


import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;



@Configuration 
@ComponentScan 
@EnableAutoConfiguration 
public class Startup {
    private static Logger log= LoggerFactory.getLogger(Startup.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @PostConstruct
    public void doSomething() {
        Gson gson=new Gson();
        String json="[\"a1:123\"]";
        log.info("json :"+json);
        //log.info("json length:"+json.length());
        
        List<String> jsonList=gson.fromJson(json, new TypeToken<List<String>>() {}.getType());
        for(int i=0;i<10;i++) {
            long start=System.currentTimeMillis();
            List<String> rstList=stringRedisTemplate.opsForValue().multiGet(jsonList);
            log.info("length:{} time:{}ms",rstList.size(),(System.currentTimeMillis()-start));
            long gsonStart=System.currentTimeMillis();           
        }
    }

    public static void main(String[] args) {
       
       
        try {
            SpringApplication.run(Startup.class, args);
        }catch(Exception e){
            log.error(e.getMessage(),e);
        }
        System.out.println("main init end...");
        
        
        
    }

}


redis操作类:


package net.highersoft;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashSet;
import java.util.Set;

@Configuration
public class LettuceFactoryInit {
    private static Logger log = LoggerFactory.getLogger(LettuceFactoryInit.class);
    @Value("${spring.redis.lettuce.pool.max-total}")
    private Integer maxTotal;

    @Value("${spring.redis.cluster.nodes}")
    private String clusterNodes;


//    @Value("${spring.redis.password}")
//    private String password;

    @Value("${spring.redis.lettuce.pool.max-idle}")
    private Integer maxIdle;

    @Value("${spring.redis.lettuce.pool.min-idle}")
    private Integer minIdle;
    @Value("${spring.redis.lettuce.pool.max-wait}")
    private Long maxWait;

    @Value("${spring.redis.timeout}")
    private Long timeOut;

    @Value("${spring.redis.lettuce.shutdown-timeout}")
    private Long shutdownTimeOut;
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
        //todo 定制化配置
        return stringRedisTemplate;
    }

    @Bean
    public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory factory, StringRedisSerializer stringRedisSerializer) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        //对key采用String的序列化方式--统一
        redisTemplate.setKeySerializer(stringRedisSerializer);
        //事务支持
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }


    @Bean
    public StringRedisSerializer getStringRedisSerializer() {
        return new StringRedisSerializer();
    }


    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory(GenericObjectPoolConfig genericObjectPoolConfig) {
        log.info("LettuceConnectionFactory connect 初始化.....");
        try {
            // 集群版配置
            RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
            String[] serverArray = clusterNodes.trim().split(",");
            Set<RedisNode> nodes = new HashSet<RedisNode>();
            for (String ipPort : serverArray) {
                String[] ipAndPort = ipPort.split(":");
                nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1].trim())));
            }
//            redisClusterConfiguration.setPassword(RedisPassword.of(password));
            redisClusterConfiguration.setClusterNodes(nodes);
            redisClusterConfiguration.setMaxRedirects(3);

            LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                    .commandTimeout(Duration.ofMillis(timeOut))
                    .poolConfig(genericObjectPoolConfig)
                    .build();
            LettuceConnectionFactory factory = new LettuceConnectionFactory(redisClusterConfiguration, clientConfig);
            factory.afterPropertiesSet();
            log.info("LettuceConnectionFactory connect successful.....");
            return factory;
        } catch (Exception ex) {
            log.info("LettuceFactoryInit exception message = {}", ex.getMessage());
            ex.printStackTrace();
        }
        return null;
    }


    @Bean
    public GenericObjectPoolConfig genericObjectPoolConfig() {
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxIdle(maxIdle);
        genericObjectPoolConfig.setMaxTotal(maxTotal);
        genericObjectPoolConfig.setMinIdle(minIdle);
        genericObjectPoolConfig.setMaxWaitMillis(maxWait);
        genericObjectPoolConfig.setEvictorShutdownTimeoutMillis(shutdownTimeOut);


        //todo 其他配置
        return genericObjectPoolConfig;
    }

}



配置文件application.properties


#logging.config=classpath:log4j2.xml
spring.redis.timeout=30000
spring.redis.database=0
spring.redis.cluster.nodes=192.168.xx.1:6001,192.168.xx.2:6001
spring.redis.lettuce.pool.max-total=500
spring.redis.lettuce.pool.max-idle=50
spring.redis.lettuce.pool.min-idle=20
spring.redis.lettuce.pool.max-wait=30000
spring.redis.lettuce.shutdown-timeout=30000



pom.xml


<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.highersoft</groupId>
  <artifactId>spring-redis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <!-- <version>1.5.2.RELEASE</version> -->
        <version>2.1.0.RELEASE</version> 
        
        <relativePath/>
    </parent>
    <dependencies>
                
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
           
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>           
        </dependency>
        
         <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        
     <dependency>
            <!-- jsoup HTML parser library @ http://jsoup.org/ -->
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.9.2</version>
        </dependency>
         <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
       
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
       
       <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.63.Final</version>
        </dependency>
        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
            <version>6.0.5.RELEASE</version>
        </dependency>
       
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.0.2</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>com.dhgate.Startup</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                </plugin>
        </plugins>
    </build>

</project>

文/程忠 浏览次数:0次   2021-10-19 13:00:19

相关阅读


评论: