SpringDataRedis(SpringData)

Introduction: In the lettuce that a written inside a database connection with lettuce, database and operating redis

Schematic:

1. dependencies

<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.1.9.RELEASE</version>
</dependency>

2.SpringData redis database connection

• create a src / main / profiles / dev / config / redis.properties configuration file, dev is the source folder. All configuration and redis-related properties in this profile.

redis.host = redis-server // ip address or host name of the database connection redis 
redis.port = 6379 // port 
redis.auth = hellolee // authentication information 
redis.database = 0 // database index number 
redis.pool .maxTotal = total number of connector connection pool 10 // maximum 
redis.pool.maxIdle = 5 // connection pool maintained maximum number of connections 
redis.pool.minIdle = 3 // connection pool maintained by the minimum number of connections 
redis.pool. after testOnBorrow = true // return all the connection test

• Add package scanning redis.properties located in src / main / resources / spring / spring-base.xml profile

<context:component-scan base-package="com.yootk.redis.config"/>

• write configuration class SpringDataRedisConfig.java

package com.yootk.redis.config;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;

@Configuration
@PropertySource("classpath:config/redis.properties")
public class SpringDataRedisConfig {
    @Bean("redisConfiguration")
    public RedisStandaloneConfiguration getRedisConfiguration(
            @Value("${redis.host}") String hostName ,
            @Value("${redis.port}") int port,
            @Value("${redis.auth}") String password,
            @Value("${redis.database}") int database
    ) {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration() ;
        configuration.setHostName(hostName); // 设置Redis主机名称
        configuration.setPort(port); // 设置Redis的访问端口
        configuration.setPassword(RedisPassword.of(password)); // 设置密码
        configuration.setDatabase(database); // 设置数据库索引
        return configuration ;
    }
    @Bean("objectPoolConfig")
    public GenericObjectPoolConfig getObjectPoolConfig(
            @Value("${redis.pool.maxTotal}") int maxTotal ,
            @Value("${redis.pool.maxIdle}") int maxIdle ,
            @Value("${redis.pool.minIdle}") int minIdle ,
            @Value("${redis.pool.testOnBorrow}") boolean testOnBorrow
    ) {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig() ;
        poolConfig.setMaxTotal (maxTotal);
    public RedisConnectionFactory getConnectionFactory (
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle (minIdle); 
        poolConfig.setTestOnBorrow (testOnBorrow); 
        return poolConfig; 
    } 
    @Bean ( "lettuceClientConfiguration") 
    public LettuceClientConfiguration getLettuceClientConfiguration ( 
            @Autowired GenericObjectPoolConfig poolConfig 
    ) {// create a client connection pool configuration object components Lettuce 
        return LettucePoolingClientConfiguration. . Builder () poolConfig (poolConfig) .build (); 
    } @Bean ( "redisConnectionFactory") // this embodiment corresponds to an example of instantiation objects redisConnectionFactory class, the foregoing contents of the object is double quotes,    // once when the rest of the automatic injection of this object, this method will be executed automatically, so the implementation of this method is equivalent to the implementation of a constructor. 
            @Autowired RedisStandaloneConfiguration redisConfiguration,
    
@Autowired LettuceClientConfiguration lettuceClientConfiguration ) { LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(redisConfiguration,lettuceClientConfiguration) ; return connectionFactory ; } }

 Redis can test whether the current normal connection, write test classes

package com.yootk.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = {"classpath:spring/*.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisConnection {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory ;
    @Test
    public void testRedis() {
        System.out.println (this.redisConnectionFactory); // output connection factory instance
        this.redisConnectionFactory.getConnection () flushDb ();. // clear the database 
    } 
}

3.RedisTemplate

• Modify configuration class SpringDataRedisConfig.java, add two methods

    @Bean("stringRedisTemplate")
    public RedisTemplate getStringRedisTempalate(
            @Autowired RedisConnectionFactory connectionFactory
    ) {
        StringRedisTemplate redisTemplate = new StringRedisTemplate() ;
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate ;
    }
    @Bean("redisTemplate")
    public RedisTemplate getRedisTempalate(
            @Autowired RedisConnectionFactory connectionFactory
    ) {
        RedisTemplate<String,String> redisTemplate = new RedisTemplate<>() ;
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate ;
    }

• Test StringRedisTemplate

package com.yootk.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@ContextConfiguration(locations = {"classpath:spring/*.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisTemplateBase {
    @Autowired
    private RedisTemplate<String, String> stringRedisTemplate;
    @Test
    public void testString() {
        for (int x = 0; x < 10; x++) {
            this.stringRedisTemplate.opsForValue().set("msg - " + x, "Hello - " + x);
        }
    }
    @Test
    public void testHash() {
        Map<String, String> map = new HashMap<>();
        map.put("name", "可爱的小李老师");
        map.put("age", String.valueOf(16));
        map.put("salary", String.valueOf(1.1));
        this.stringRedisTemplate.opsForHash().putAll("member-lee", map);
        System.out.println(this.stringRedisTemplate.opsForHash().get("member-lee","name"));
    public void testKeys () {
    @Test
    }
        Set<String> keys = this.stringRedisTemplate.keys("msg - *");
}
    }
        System.out.println ( "all [key]" + Keys);

• Test RedisTemplate

package com.yootk.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = {"classpath:spring/*.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisTemplate {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void testString() {
        this.redisTemplate.execute(new RedisCallback<Object>() {    // Redis回调
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushDb(); // 清空数据库
                return "ok";
            }
        }) ;
        for (int x = 0; x < 10; x++) {
            this.redisTemplate.opsForValue().set("message-" + x, "Hello - " + x);
        }
    }
    @Test
    public void testGet() {
        System.err.println("【获取数据】" + this.redisTemplate.opsForValue().get("message-3"));
    }
}

4. The sequence of stored objects: object stored in the class database redis, stressed: corresponding to the object class must implement Serializable.

  And StringRedisTemplate the difference RedisTemplate: StringRedisTemplate RedisTemplate is provided a series string of process sequence.

  In SpringDataRedis processing operations inside the target sequence in two ways: JDK serialization processing mechanism based on JSON serialization mechanism. If the java code is achieved by Oh, and will fully take into account the performance of the JDK mechanism is used, considering the versatility of use of the data is JSON mechanism.

• Use JDK mechanism for storing objects, modify the configuration class SpringDataRedisConfig.java

@Bean ( "redisTemplate") // changed the original method getRedisTempalate now 
    public RedisTemplate getRedisTempalate ( 
            @Autowired RedisConnectionFactory The connectionFactory 
    ) { 
        RedisTemplate <String, Object> = new new RedisTemplate redisTemplate <> (); 
        redisTemplate.setConnectionFactory (The connectionFactory); 
        redisTemplate.setKeySerializer (new StringRedisSerializer ()); key data of // string storage 
        redisTemplate.setValueSerializer (new JdkSerializationRedisSerializer ()); // save the value of the object 
        redisTemplate.setHashKeySerializer (new StringRedisSerializer ()); // data key string is stored by 
        redisTemplate.setHashValueSerializer (new JdkSerializationRedisSerializer ()); // save the value of the object 
        return redisTemplate;
    }

• Using JSON mechanism for storing objects, modify the configuration class SpringDataRedisConfig.java 

    @Bean ( "redisTemplate") // changed the original method getRedisTempalate now 
    public RedisTemplate getRedisTempalate ( 
            @Autowired RedisConnectionFactory The connectionFactory 
    ) { 
        RedisTemplate <String, Object> = new new RedisTemplate redisTemplate <> (); 
        redisTemplate.setConnectionFactory (The connectionFactory); 
        redisTemplate.setKeySerializer (new StringRedisSerializer ()); key // string data stored by 
        redisTemplate.setValueSerializer (new Jackson2JsonRedisSerializer (Object.class)) ; // save the value of the object 
        redisTemplate.setHashKeySerializer (new StringRedisSerializer ()); / / key data string stored by 
        redisTemplate.setHashValueSerializer (new Jackson2JsonRedisSerializer (Object.class)) ; // save the value of the object
        return redisTemplate ;
    }

5.Pipeline line (details see notes)

Guess you like

Origin www.cnblogs.com/wxl123/p/11110392.html