SpringBoot2.x 集成redis

目录

1.导依赖

2.修改application.yml

3.配置RedisTemplate


 1.导依赖

pom.xml 添加

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

2.修改application.yml

yml文件配置:

database:redis数据库默认有16个(0-15),这里我们使用第1个

host:虚拟机的地址,所以这里我开启了虚拟机

port:默认端口号为6379

password:由于我在我在虚拟机配置redis时没有设置密码,这里我就不使用密码

spring: 
  redis:
    #数据库索引
    database: 0
    host: 118.24.11.111
    port: 6379
    #password: 123456
    jedis:
      pool:
        #最大连接数
        max-active: 8
        #最大阻塞等待时间(负数表示没限制)
        max-wait: -1
        #最大空闲
        max-idle: 8
        #最小空闲
        min-idle: 0
    #连接超时时间
    timeout: 10000

3.配置RedisTemplate

RedisTemplate配置,重写key和value的序列化

RedisTemplate:

package com.zking.springboot02.config;

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration  //注解 配置类
public class RedisConfig {

    @Bean  //<bean id="redisTemplate" class=""></bean>
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer); // key序列化
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // value序列化
        redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); // Hash value序列化
        redisTemplate.afterPropertiesSet();
        return redisTemplate;

    }

}

测试代码:这里我使用的是junit5

@Test
void testRedis() {
   Book b = bookService.selectByPrimaryKey(11);
   redisTemplate.opsForValue().set(b.getBookId()+"",b);
}

测试成功后,我们就可以在redis可视化工具中看到第0个数据库有一条我查询到的数据了,

到这里,我们的redis就集成完成了!

今天的学习记录就到这了,拜拜!

说明:学习记录,若有错误,欢迎指正,若有疑问,欢迎评论    

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值