从contos7 安装Redis到SpringBoot中使用Redis

从contos7 安装Redis到SpringBoot中使用Redis,第1张

为演示方便, 这里使用虚拟机代替服务器

1. 下载Redis

        官网: CRUG网站

2. 上传压缩包(以Xshell为例)

 然后将压缩包拖入其中即可

3. 解压

tar -zxvf 文件名 -C 解压路径

4. 安装

4.1 cd进入目录

cd redis-6.2.1

 4.2 安装c相关

yum -y install gcc-c++ automake autoconf

4.3 编译

make

如果出现以下错误

 只需要执行以下指令即可(不需要再次执行make指令)

make MALLOC-libc

4.4 安装

make PREFIX-安装路径 install

 4.5 添加配置

将压缩包解压出来的redis中的redis.conf文件复制到安装的redis/bin中即可

# 根据自己的路径来
cp redis.conf ../redis/bin

 到这里你的Redis便安装完成了

前台启动Redis(不推荐), 于redis/bin下执行指令

./redis-server

 ctrl+C结束运行

接下来讲以下基础配置

5. 基础配置

打开复制过来的redis.conf

vim redis.conf

5.1 关闭只允许本机访问

将以下信息注释

 5.2 关闭本机访问模式

将以下信息改为no

 5.3 配置后台启动

将no改为yes

 5.4 设置密码

将如下信息取消注释, 将foobared改为你的密码即可

若不设置密码, 访问redis时便不需要输入密码

 相关配置就介绍这么多, 其他只能各位下去了解了

后台启动(推荐), 指定配置文件运行

./redis-server redis.conf

查看运行状态

ps -ef|grep redis

接下来让我们看看springboot如何使用Redis

6. springboot中应用redis

相关依赖



    org.springframework.boot
    spring-boot-starter-data-redis



     org.apache.commons
     commons-pool2

核心配置(以yml文件为例)

spring:
  redis:
#    服务器地址
    host: 192.168.73.140
#    端口,默认6397
    port: 6379
#    数据库,默认是0
    database: 0
#    超时时间
    connect-timeout: 10000ms
#   若没有密码则不加
    password: 123456
#    连接池
    lettuce:
      pool:
#        最大连接数,默认是8
        max-active: 8
#        最大阻塞等待时间
        max-wait: 10000ms
#        最大空闲连接,默认是8
        max-idle: 8
#        最小空闲连接,默认是0
        min-idle: 0

 实现序列化

package com.SecKill.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.StringRedisSerializer;

/**
 * @Author: 新写的旧代码
 * @Description: Redis配置
 * @CreateTime: 2022/4/11
 */
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate redisTemplate = new RedisTemplate<>();
        // key的序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // value的序列化
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // hash类型 key的序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // hash类型value的序列化
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

}

在使用时需要引入资源(泛型根据实际需要选择)

@Autowired
private RedisTemplate redisTemplate;

例: 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/724013.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存