ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

SpringDataRedis(SpringData)

2019-06-30 18:48:51  阅读:234  来源: 互联网

标签:SpringData redis springframework org import SpringDataRedis public redisTemplate


介绍:在lettuce那一篇里面写了用lettuce连接数据库,并且操作redis数据库

结构图:

1.依赖包

<!-- 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数据库

•  先创建一个src/main/profiles/dev/config/redis.properties配置文件,dev为源文件夹。在此配置文件中配置所有与redis有关的属性。

redis.host=redis-server//redis数据库连接的主机名称或ip地址
redis.port=6379 //连接端口
redis.auth=hellolee   //认证信息
redis.database=0  //数据库的索引编号
redis.pool.maxTotal=10  //连接池最大的总连接数量
redis.pool.maxIdle=5   //连接池维持的最大连接数量
redis.pool.minIdle=3  //连接池维持的最小的连接数量
redis.pool.testOnBorrow=true  //所有的连接测试后返回

•  在src/main/resources/spring/spring-base.xml配置文件中添加扫描redis.properties所在的包

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

•编写配置类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);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setTestOnBorrow(testOnBorrow);
        return poolConfig ;
    }
    @Bean("lettuceClientConfiguration")
    public LettuceClientConfiguration getLettuceClientConfiguration(
            @Autowired GenericObjectPoolConfig poolConfig
    ) { // 创建Lettuce组件的连接池客户端配置对象
        return LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build() ;
    }
    @Bean("redisConnectionFactory")//相当于在这例实例化了RedisConnectionFactory类的实例化对象,前面双引号中的内容就是对象,
   //一旦在其他地方自动注入此对象的时候,此方法便自动执行,所以执行此方法就相当于执行了一个构造方法。 public RedisConnectionFactory getConnectionFactory( @Autowired RedisStandaloneConfiguration redisConfiguration , @Autowired LettuceClientConfiguration lettuceClientConfiguration ) { LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(redisConfiguration,lettuceClientConfiguration) ; return connectionFactory ; } }

 测试当前的Redis是否可以正常连接,编写测试类

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);    // 输出连接工厂实例
        this.redisConnectionFactory.getConnection().flushDb();  // 清空数据库
    }
}

3.RedisTemplate

• 修改配置类SpringDataRedisConfig.java,添加两个方法

    @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 ;
    }

• 测试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"));
    }
    @Test
    public void testKeys() {
        Set<String> keys = this.stringRedisTemplate.keys("msg - *");
        System.out.println("【所有的key】" + keys);
    }
}

• 测试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. 对象序列化存储:在redis数据库中存放类的对象,强调:对象对应的类一定要实现Serializable接口。

  RedisTemplate与StringRedisTemplate的区别:StringRedisTemplate是设置了一系列字符串序列化处理的RedisTemplate。

  在SpringDataRedis里面对象序列化处理操作有两种方式:基于JDK的序列化处理机制,基于JSON的序列化处理机制。如果哦代码通过java实现,并且充分考虑到性能则使用JDK的机制,如果考虑到数据的通用性则使用JSON机制。

•  使用JDK机制存储对象,修改配置类SpringDataRedisConfig.java

 @Bean("redisTemplate")//将原来的getRedisTempalate方法改成现在这个
    public RedisTemplate getRedisTempalate(
            @Autowired RedisConnectionFactory connectionFactory
    ) {
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>() ;
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); // 保存的value为对象
        redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); // 保存的value为对象
        return redisTemplate ;
    }

•  使用JSON机制存储对象,修改配置类SpringDataRedisConfig.java 

    @Bean("redisTemplate")//将原来的getRedisTempalate方法改成现在这个
    public RedisTemplate getRedisTempalate(
            @Autowired RedisConnectionFactory connectionFactory
    ) {
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>() ;
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class)); // 保存的value为对象
        redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer(Object.class)); // 保存的value为对象
        return redisTemplate ;
    }

5.Pipeline流水线(详情见笔记)

标签:SpringData,redis,springframework,org,import,SpringDataRedis,public,redisTemplate
来源: https://www.cnblogs.com/wxl123/p/11110392.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有