SpringBoot与Redis整合的一个小项目(附全部代码)

本文详细介绍了如何在Spring Boot项目中整合Redis,包括引入依赖、配置Redis、编写序列化工具类、配置类、Controller类及测试过程。

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

1、引入redis的依赖:

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
      <version>2.0.0.RELEASE</version>
</dependency>

2、假设我们要操作的类是Coffee类:

package com.learn.coffee.entity;

import java.io.Serializable;

public class Coffee implements Serializable {
    private int coffeeId;
    private String coffeeName;
    private String coffeeKinds;
    private String coffeeDiscount;
    private int newPrice;
    private int oldPrice;
    private String coffeeImage;

    public int getCoffeeId() {
        return coffeeId;
    }

    public void setCoffeeId(int coffeeId) {
        this.coffeeId = coffeeId;
    }

    public String getCoffeeName() {
        return coffeeName;
    }

    public void setCoffeeName(String coffeeName) {
        this.coffeeName = coffeeName;
    }

    public String getCoffeeKinds() {
        return coffeeKinds;
    }

    public void setCoffeeKinds(String coffeeKinds) {
        this.coffeeKinds = coffeeKinds;
    }

    public String getCoffeeDiscount() {
        return coffeeDiscount;
    }

    public void setCoffeeDiscount(String coffeeDiscount) {
        this.coffeeDiscount = coffeeDiscount;
    }

    public int getNewPrice() {
        return newPrice;
    }

    public void setNewPrice(int newPrice) {
        this.newPrice = newPrice;
    }

    public int getOldPrice() {
        return oldPrice;
    }

    public void setOldPrice(int oldPrice) {
        this.oldPrice = oldPrice;
    }

    public String getCoffeeImage() {
        return coffeeImage;
    }

    public void setCoffeeImage(String coffeeImage) {
        this.coffeeImage = coffeeImage;
    }
}

这里一定要注意,该类一定要实现Serializable接口。

3、编写序列化和反序列化的工具类:

package com.learn.coffee.utils;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

public class ObjectRedisSerializer implements RedisSerializer<Object> {

    /**
     * 定义序列化和反序列化转化类
     */
    private Converter<Object,byte[]> serializer=new SerializingConverter();
    private Converter<byte[],Object> deserializer=new DeserializingConverter();

    /**
     * 定义转换空字节数组
     */
    private final static byte[] EMPTY_ARRAY=new byte[0];

    @Override
    public byte[] serialize(Object obj) throws SerializationException {
        byte[] byteArr=null;
        if(null==obj){
            System.out.println("----------------------------------->:Redis待序列化的对象为空");
            byteArr=EMPTY_ARRAY;
        }
        else {
            try {
                byteArr=serializer.convert(obj);
            }catch (Exception ex){
                System.out.println("------------------------------->:Redis序列化对象失败,异常:"+ ex.getMessage());
                byteArr=EMPTY_ARRAY;
            }
        }
        return byteArr;
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        Object obj=null;
        if((null==bytes)||(bytes.length==0)){
            System.out.println("-------------------------------->:Redis反序列化对象为空");
        }
        else {
            try {
                obj=deserializer.convert(bytes);
            }catch (Exception ex){
                System.out.println("------------------------------->:Redis反序列化对象失败,异常:"+ ex.getMessage());
            }
        }
        return obj;
    }
}

4、redis的springboot配置类,这里我采用了类实现,而不是xml实现。

package com.learn.coffee.config;

import com.learn.coffee.utils.ObjectRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<Serializable,Object> redisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<Serializable,Object> template=new RedisTemplate<Serializable,Object>();
        template.setConnectionFactory(connectionFactory);
        template.afterPropertiesSet();
        //redis存取对象的关键配置
        template.setKeySerializer(new StringRedisSerializer());
        //ObjectRedisSerializer类为java对象的序列化和反序列化工具类
        template.setValueSerializer(new ObjectRedisSerializer());
        return template;
    }
}

5、编写application.yml配置文件

spring:
  # REDIS
  redis:
    # Redis数据库索引(默认为0)
    database: 0
    # Redis服务器地址 (默认为127.0.0.1)
    host: 127.0.0.1
    # Redis服务器连接端口 (默认为6379)
    post: 6379
    # Redis服务器连接密码(默认为空)
    password: 123456
    # 连接超时时间(毫秒)
    timeout: 2000

这里我采用了yml文件编写,笔者也可以使用application.properties进行编写,只需了解他们的区别即可。

6、编写Controller类

package com.learn.coffee.controller;

import com.learn.coffee.entity.Coffee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisTemplate<Serializable,Object> redisTemplate;

    @RequestMapping("/setCoffee")
    public boolean setCoffee(){

        Coffee coffee=new Coffee();
        coffee.setCoffeeId(90);
        coffee.setCoffeeName("热水");
        coffee.setCoffeeKinds("直男专属");
        coffee.setCoffeeDiscount("五折");
        coffee.setNewPrice(10);
        coffee.setOldPrice(20);
        coffee.setCoffeeImage("123.jpg");
        redisTemplate.opsForValue().set("coffee90",coffee);
        return true;
    }

    @RequestMapping("/getCoffee")
    public Object getCoffee(){
        return redisTemplate.opsForValue().get("coffee90");
    }

}

7、测试:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值