springboot整合redis

本文介绍了如何在SpringBoot项目中集成Redis,包括在创建项目时选择NOSQL的Redis选项,配置`application.properties`文件,创建RedisUtil工具类进行基本的Redis操作,并在测试类中验证存取功能。同时,还展示了使用Jackson2JsonRedisSerializer进行序列化配置。
摘要由CSDN通过智能技术生成

在创建springboot的时候

勾选NOSQL中的redis

编写application.properties

spring.redis.host=你的地址
spring.redis.password=你的密码

创建util包

package com.redis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtils {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void set(String key,String value){
        redisTemplate.opsForValue().set(key,value);
    }

    public String get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public void hset(String key,String field,Object value){
        redisTemplate.opsForHash().put(key,field,value);
    }

    public Object hget(String key,String field){
        return  redisTemplate.opsForHash().get(key,field);
    }
}

在test测试里面

package com.redis;

import com.redis.util.RedisUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class RedisApplicationTests {

    @Autowired
    RedisUtils redisUtils;

    /**
     * 测试存入
     */
    @Test
    void contextLoads() {
        redisUtils.set("msg","hello");
        String msg=redisUtils.get("msg");
        System.out.println(msg);
    }

}

序列化

package com.money.lin.util;

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.Jackson2JsonRedisSerializer;


@Configuration
public class RedisUtil {


    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        //指定键值
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);

        return redisTemplate;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值