springboot集成redis (单个redis或多个redis)

本文详细介绍了如何在SpringBoot项目中集成单个和多个Redis实例。首先,通过添加maven依赖和配置文件设置Redis连接信息。接着,自定义RedisConfig类以配置RedisTemplate。在代码中,展示了存取JSON字符串和Bean对象的操作。对于多个Redis实例,同样配置额外的Redis信息并创建新的RedisTemplate实例,实现了数据在不同Redis实例间的存取。
摘要由CSDN通过智能技术生成

目标:

1、springboot集成单个redis,并通过代码操作redis;

2、springboot集成多个redis,并通过代码操作redis;

一、springboot集成单个redis

1、引入maven依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.54</version>
</dependency>

2、添加redis配置信息

spring.redis.host=10.0.99.35

spring.redis.port=6379

spring.redis.database=12

spring.redis.password=

3、编写RedisConfig类配置RedisTemplate

 

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置
 *
 * @author lihaifei
 * @since 2020-05-15
 */
@Configuration
public class RedisConfig {
    @Autowired
    private RedisConnectionFactory factory;

    @Bean
    @Primary
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

4、代码中操作redis

演示:

1、存取json字符串

2、存取bean对象

 

public class TestController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/testSetAndGet")
    public Object test1(){
        logger.info("id={},name={},start...",Thread.currentThread().getId(),Thread.currentThread().getName());
        JSONObject re
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值