Java框架_SpringBoot整合Spring Data Redis

本文详细介绍如何在 Spring Boot 应用中整合 Redis,并演示了使用 Spring Data Redis 操作 Redis 的过程,包括基本配置、实体类操作及 JSON 格式的存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • Redis版本:3.0.0
  • 运行环境:Linux

1 安装Redis

1.1安装gcc

Yum installgcc-c++

1.2 解压redis.3.0.0.tar.gz压缩包

tar -zxvfredis-3.0.0.tar.gz

1.3 进入解压后的目录进行编译

cd redis-3.0.0

make

1.4 将Redis安装到指定目录

makePREFIX=/usr/local/redis install

1.5 启动Redis

./redis-server

2 Spring Boot整合Spring Data Redis

Spring Data Redis是属于Spring Data下的一个模块。作用就是简化对于redis的操做

2.1 修改pom文件添加Spring Data Redis的坐标

<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">

  <modelVersion>4.0.0</modelVersion>

  <parent>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-parent</artifactId>

    <version>1.5.10.RELEASE</version>

  </parent>

  <groupId>com.bjsxt</groupId>

  <artifactId>24-spring-boot-redis</artifactId>

  <version>0.0.1-SNAPSHOT</version>

 

  <properties>

  <java.version>1.7</java.version>

  <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>

  <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>

  </properties>

 

  <dependencies>

    <!-- springBoot的启动器 -->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

    </dependency>

    <!-- thymeleaf的启动器 -->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-thymeleaf</artifactId>

    </dependency>

   

    <!-- Spring Data Redis的启动器 -->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-data-redis</artifactId>

    </dependency>

  </dependencies>

</project>


2.2  编写Spring DataRedis的配置类(重点)

/**

 * 完成对Redis的整合的一些配置

 *

 *

 */

@Configuration

publicclass RedisConfig {

 

    /**

     * 1.创建JedisPoolConfig对象。在该对象中完成一些链接池配置

     *

     */

    @Bean

    public JedisPoolConfig jedisPoolConfig(){

        JedisPoolConfig config = new JedisPoolConfig();

        //最大空闲数

        config.setMaxIdle(10);

        //最小空闲数

        config.setMinIdle(5);

        //最大链接数

        config.setMaxTotal(20);

       

        returnconfig;

    }

   

    /**

     * 2.创建JedisConnectionFactory:配置redis链接信息

     */

    @Bean

    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config){

        JedisConnectionFactory factory = new JedisConnectionFactory();

        //关联链接池的配置对象

        factory.setPoolConfig(config);

        //配置链接Redis的信息

        //主机地址

        factory.setHostName("192.168.70.128");

        //端口

        factory.setPort(6379);

       

        returnfactory;

    }

   

    /**

     * 3.创建RedisTemplate:用于执行Redis操作的方法

     */

    @Bean

    public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory){

        RedisTemplate<String, Object> template = new RedisTemplate<>();

        //关联

        template.setConnectionFactory(factory);

       

        //为key设置序列化器

        template.setKeySerializer(new StringRedisSerializer());

        //为value设置序列化器

        template.setValueSerializer(new StringRedisSerializer());

       

        returntemplate;

    }

}

 

2.3     编写测试代码,测试整合环境
2.3.1        修改pom文件添加测试启动器坐标

 <!-- Test的启动器 -->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

    </dependency>

2.3.2  编写测试类

/**

 * Spring Data Redis测试

 *

 *

 */

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest(classes=App.class)

publicclass RedisTest {

 

    @Autowired

    private RedisTemplate<String, Object> redisTemplate;

   

    /**

     * 添加一个字符串

     */

    @Test

    publicvoid testSet(){

        this.redisTemplate.opsForValue().set("key", "北京尚学堂");

    }

   

    /**

     * 获取一个字符串

     */

    @Test

    publicvoid testGet(){

        String value = (String)this.redisTemplate.opsForValue().get("key");

        System.out.println(value);

    }

}


3   提取redis的配置信息

3.1 在src/main/resource/目录下新建一个配置文件:application.properties

spring.redis.pool.max-idle=10

spring.redis.pool.min-idle=5

spring.redis.pool.max-total=20

 

spring.redis.hostName=192.168.70.128

spring.redis.port=6379


3.2     修改配置类

/**

 * 完成对Redis的整合的一些配置

 *

 *

 */

@Configuration

publicclass RedisConfig {

 

    /**

     * 1.创建JedisPoolConfig对象。在该对象中完成一些链接池配置

     * @ConfigurationProperties:会将前缀相同的内容创建一个实体。

     */

    @Bean

    @ConfigurationProperties(prefix="spring.redis.pool")

    public JedisPoolConfig jedisPoolConfig(){

        JedisPoolConfig config = new JedisPoolConfig();

        /*//最大空闲数

        config.setMaxIdle(10);

        //最小空闲数

        config.setMinIdle(5);

        //最大链接数

        config.setMaxTotal(20);*/

        System.out.println("默认值:"+config.getMaxIdle());

        System.out.println("默认值:"+config.getMinIdle());

        System.out.println("默认值:"+config.getMaxTotal());

        returnconfig;

    }

   

    /**

     * 2.创建JedisConnectionFactory:配置redis链接信息

     */

    @Bean

    @ConfigurationProperties(prefix="spring.redis")

    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig config){

        System.out.println("配置完毕:"+config.getMaxIdle());

        System.out.println("配置完毕:"+config.getMinIdle());

        System.out.println("配置完毕:"+config.getMaxTotal());

       

        JedisConnectionFactory factory = new JedisConnectionFactory();

        //关联链接池的配置对象

        factory.setPoolConfig(config);

        //配置链接Redis的信息

        //主机地址

        /*factory.setHostName("192.168.70.128");

        //端口

        factory.setPort(6379);*/

        returnfactory;

    }

   

    /**

     * 3.创建RedisTemplate:用于执行Redis操作的方法

     */

    @Bean

    public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory factory){

        RedisTemplate<String, Object> template = new RedisTemplate<>();

        //关联

        template.setConnectionFactory(factory);

       

        //为key设置序列化器

        template.setKeySerializer(new StringRedisSerializer());

        //为value设置序列化器

        template.setValueSerializer(new StringRedisSerializer());

       

        returntemplate;

    }

}

 


4  Spring Data Redis操作实体对象

4.1.1 创建实体类

publicclass Users implements Serializable {

   

    private Integer id;

    private String name;

    private Integer age;

    public Integer getId() {

        returnid;

    }

    publicvoid setId(Integer id) {

        this.id = id;

    }

    public String getName() {

        returnname;

    }

    publicvoid setName(String name) {

        this.name = name;

    }

    public Integer getAge() {

        returnage;

    }

    publicvoid setAge(Integer age) {

        this.age = age;

    }

    @Override

    public String toString() {

        return"Users [id=" + id + ", name=" + name + ", age=" + age + "]";

    }

   

}

 


4.1.2        测试代码

/**

     * 添加Users对象

     */

    @Test

    publicvoid testSetUesrs(){

        Users users = new Users();

        users.setAge(20);

        users.setName("张三丰");

        users.setId(1);

        //重新设置序列化器

        this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());

        this.redisTemplate.opsForValue().set("users", users);

    }

   

    /**

     * 取Users对象

     */

    @Test

    publicvoid testGetUsers(){

        //重新设置序列化器

        this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());

        Users users = (Users)this.redisTemplate.opsForValue().get("users");

        System.out.println(users);

    }


5  Spring Data Redis以JSON格式存储实体对象

5.1     测试代码

/**

     * 基于JSON格式存Users对象

     */

    @Test

    publicvoid testSetUsersUseJSON(){

        Users users = new Users();

        users.setAge(20);

        users.setName("李四丰");

        users.setId(1);

        this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));

        this.redisTemplate.opsForValue().set("users_json", users);

    }

   

    /**

     * 基于JSON格式取Users对象

     */

    @Test

    publicvoid testGetUseJSON(){

        this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Users.class));

        Users users = (Users)this.redisTemplate.opsForValue().get("users_json");

        System.out.println(users);

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值