Ubuntu上安装、使用Redis的详细教程

news2024/10/5 13:07:54

这篇文章简单地介绍一下怎么在linux虚拟机上完成redis的安装及使用。

 

目录

1、安装redis

2、使用redis

3、启动/关闭redis

启动redis

启动方式一

启动方式二

启动方式三

重启redis

关闭redis

查看redis状态

4、在宿主机连接redis

5、通过java连接redis

创建maven项目

添加jedis的依赖

jedis的案例代码

关闭保护模式

重新运行代码


1、安装redis

首先,访问Redis官网,点击首页的【Get Started】,然后点击Install Redis on Linux

5a94afcbb155403c89c2642506481360.png

然后按照页面内容提示,在Ubuntu上安装redis

9f79dc1156bd43c9bc7ba420b422ffb0.png

只需要在终端依次输入以下命令,如果过程中没有错误提示,则redis安装完成。

sudo apt install lsb-release curl gpg
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt-get update
sudo apt-get install redis

2、使用redis

在终端输入redis-cli,会进入到redis的命令行模式,这时候就可以愉快地使用redis的各种命令了。

输入exit退出redis-cli。

2206a0bb88054553bb86327f9f799a79.png

3、启动/关闭redis

启动redis

启动方式一

/etc/init.d/redis-server start

启动方式二

systemctl start redis-server

启动方式三

service redis-server start

重启redis

service redis-server restart

关闭redis

service redis-server stop

查看redis状态

service redis-server status

4、在宿主机连接redis

根据以上步骤安装启动redis后,默认只能在虚拟机内访问redis,如果在其他机器上访问,需要修改配置文件。

默认情况下,redis的配置文件在/etc/redis/redis.conf,打开这个文件,注释掉下面的内容。

bind 127.0.0.1 -::1

然后就可以在windows上通过Another Redis Desktop Manager连接ubuntu上的redis了,当然了,如果你希望给redis设置一个密码,可以在配置文件中加上以下的配置。

requirepass 你的密码

设置完之后,不输入密码连接时会提示

5、通过java连接redis

redis官方推荐通过jedis来操作redis,jedis是一个专门设计用于操作和快速使用redis的Java客户端。

Jedis is a Java client for Redis designed for performance and ease of use.

如图,点击Client quikstart,在点击展开的Java。

如图,官网已经给出了操作redis的方法

 

创建maven项目

在IntelliJ IDEA创建一个maven项目:依次File -> New -> Project...

然后在左侧选择Maven,然后点击Next

然后填写项目名和包名

最后点击Finish就完成Maven项目的创建了。

添加jedis的依赖

在pom.xml中添加jedis客户端依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.3.1</version>
</dependency>

完整的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>redis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>4.3.1</version>
        </dependency>
    </dependencies>
</project>

 

jedis的案例代码

package com.example.redis;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

@SpringBootTest
class RedisTests {

    @Test
    void contextLoads() {
        JedisPool pool = new JedisPool("192.168.254.128", 6379);

        try (Jedis jedis = pool.getResource()) {
            jedis.set("foo", "bar");
            System.out.println(jedis.get("foo"));

            Map<String, String> hash = new HashMap<>();

            hash.put("name", "John");
            hash.put("surname", "Smith");
            hash.put("company", "Redis");
            hash.put("age", "29");

            jedis.hset("user-session:123", hash);

            System.out.println(jedis.hgetAll("user-session:123"));
        }
    }

}

 

关闭保护模式

运行上面测试类,正常来说会看到绿条,但是运行的时候发生了异常

以下是控制台打印的异常信息

redis.clients.jedis.exceptions.JedisDataException: DENIED Redis is running in protected mode because protected mode is enabled and no password is set for the default user. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. 3) If you started the server manually just for testing, restart it with the '--protected-mode no' option. 4) Set up an authentication password for the default user. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.

	at redis.clients.jedis.Protocol.processError(Protocol.java:96)
	at redis.clients.jedis.Protocol.process(Protocol.java:137)
	at redis.clients.jedis.Protocol.read(Protocol.java:192)
	at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:316)
	at redis.clients.jedis.Connection.getOne(Connection.java:298)
	at redis.clients.jedis.Connection.executeCommand(Connection.java:123)
	at redis.clients.jedis.Jedis.set(Jedis.java:4880)
	at com.example.redis.RedisTests.contextLoads(RedisTests.java:19)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
	at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
	at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
	at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
	at java.util.ArrayList.forEach(ArrayList.java:1257)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
	at java.util.ArrayList.forEach(ArrayList.java:1257)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
	at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

抓到其中的一个关键词:protected-mode,很显然,这应该是一个配置

'CONFIG SET protected-mode no'

于是我们到redis.conf下搜索一下这个设置,果然找到了,先把这个设置yes改成no

修改为no

然后重启一下redis

service redis-server restart

重新运行代码

再次运行之前的代码,这一次成功了

然后接着往下看,redis还提供了不用写try...catech块的方式操作redis,这样代码看起来更简洁了

同样,复制代码运行一次,也运行成功了

最后,通过Another Redis Desktop Manager连接虚拟机上的redis,能看到刚刚运行设置的key

没有用过Another Redis Desktop Manager的童鞋,可以通过以下文章了解一下:

redis桌面连接工具Another Redis Desktop Manager使用介绍icon-default.png?t=N7T8https://blog.csdn.net/heyl163_/article/details/133007448

好了,关于安装和使用redis的介绍就到这里了,看完不要忘了点赞+收藏哦~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1034338.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Webpack监视文件修改,自动重新打包文件

方法一&#xff1a;使用watch监视文件变化 在终端中输入以下指令&#xff1a; npx webpack --watch 我们使用这种方法监听文件变化时只会监听我们计算机本地的文件变化&#xff0c;在开发场景中我们的项目是要部署到服务器中的&#xff0c;因此这种方式并不推荐。 方法二&…

proteus中的各种电阻-可变电阻-排阻

在原理图中使用各类型的电阻是很常见的事情&#xff0c;尤其类似与排阻、可变电阻&#xff0c;但这些电阻对于不熟悉proteus的童鞋来说&#xff0c;一下子可能很难找到&#xff0c;或者很难找心中所想的那个类型&#xff0c;这里分类列出&#xff0c;便于大家使用。 文章目录 一…

Kubernetes集群+Keepalived+Nginx+防火墙实例

文章目录 实验前期规划1.拓扑图结构2.实验要求3.实验环境规划 一.kubeadm 部署 K8S 集群架构1.环境准备2.三个节点安装docker3.三个节点安装kubeadm&#xff0c;kubelet和kubectl4.部署K8S集群&#xff08;1&#xff09;初始化&#xff08;2&#xff09;部署网络插件flannel&am…

腾讯云COS+Picgo+Typora图床搭建

文章目录 什么是图床&#xff1f;配置腾讯云COS整体流程注册腾讯云账号并开通配置COS下载并配置PicGoTypora配置PicGo 可视化管理工具 什么是图床&#xff1f; 百度百科是这样解释的&#xff1a; 图床一般是指储存图片的服务器&#xff0c;有国内和国外之分。国外的图床由于有…

2023-9-22 整数划分

题目链接&#xff1a;整数划分 转化成背包问题 #include <iostream> #include <algorithm>using namespace std;const int N 1010, mod 1e9 7;int n; int f[N];int main() {cin >> n;f[0] 1;// i 相当于第i个物品的体积for(int i 1; i < n; i )// j …

计算机视觉: 三维物体生成

三维物体生成与编辑 论文地址: Controllable Mesh Generation Through Sparse Latent Point Diffusion Models 背景 数据是目前数字化和AI领域最宝贵的财富之一&#xff0c;但是对于目前的开发者来说&#xff0c;收集数据都意味着极大的成本。所以建立一个高效的生成模型能极…

Fair原理篇之Fair逻辑动态化通信实现

Fair 逻辑动态化,是对一期布局动态化的增强。为了实现逻辑动态化,我们当时考虑了多种方案,方案主要集中在这三个方面,一种是对google提供的JIT进行裁切,第二种是自定义解析引擎,第三种借助js的能力。 下面主要讲一下几方面: 架构的标准化通信协议的实现js文件的加载与释…

MongoDB 是什么和使用场景概述(技术选型)

一、从NOSQL(Not Only SQL)说起 常见的数据库可以分为下面的两种类型&#xff1a; RDBMS&#xff08;关系型数据库&#xff09;&#xff1a;常见的关系型数据库有 Oracle、DB2、Microsoft SQL Server、Microsoft Access、MySQL&#xff1b;NoSQL&#xff08;非关系型数据库&a…

计算机视觉与深度学习-循环神经网络与注意力机制-RNN(Recurrent Neural Network)、LSTM-【北邮鲁鹏】

目录 举例应用槽填充&#xff08;Slot Filling&#xff09;解决思路方案使用前馈神经网络输入1-of-N encoding(One-hot)&#xff08;独热编码&#xff09; 输出 问题 循环神经网络&#xff08;Recurrent Neural Network&#xff0c;RNN&#xff09;定义如何工作深度Elman Netwo…

DAB-DETR

DAB-DETR&#xff08;2022ICLR&#xff09; DAB&#xff1a;Dynamic Anchor Boxes 贡献&#xff1a; 明确了不是由于learnable queries导致的收敛缓慢 4D anchor Anchor Update Width & Height Modulated Temperature Tuning 前半部分&#xff1a;Why a positional …

每日一题~将有序数组转换为二叉搜索树

原题链接&#xff1a;108. 将有序数组转换为二叉搜索树 - 力扣&#xff08;LeetCode&#xff09; 题目描述&#xff1a; 思路分析&#xff1a; 今天这道题比较简单&#xff0c;我们看一下数组和树之间的联系很容易就能发现规律。 通过简单观察我们发现&#xff0c;位于数组中…

CSDN博客去水印方法

直接在 创作中心->博客 设置这里关了好像就行了&#xff0c;之前方法是找图片链接?后面的一大串字符给去掉。

Java由浅入深理解线程池设计和原理

目录 1 线程1.1 什么是线程&#xff1f;什么是进程&#xff1f;1.2 java中线程的实现方式有几种?1.3 线程的生命周期是什么&#xff1f; 2 线程存在的问题2.1 一个线程只能执行一个任务2.2 线程执行完后销毁,无法复用2.3 线程过多,导致JVM宕机 3 初识线程池3.1 了解J.U.C3.2 线…

计网第五章(运输层)(六)(TCP可靠传输的实现)

目录 一、基本概述 二、具体实现 1.前后沿&#xff1a; 2.利用指针描述发送窗口的状态 3.有差错情况 之前在数据链路层时已经讨论过可靠传输&#xff08;计网第三章&#xff08;数据链路层&#xff09;&#xff08;二&#xff09;&#xff08;可靠传输&#xff09;&#x…

电表智能管理系统-实现智能化、数字化的电力管理

随着信息技术的发展&#xff0c;智能电表已经成为了现代电力管理的重要组成部分。智能电表能够实时监测和记录用电量&#xff0c;自动控制用电&#xff0c;从而实现更加智能、高效的电力管理。 智能电表是一种能够自动监测和记录用电量&#xff0c;并能够自动控制用电的设备…

IDEA中取消双击shift全局搜索

设置如图步骤&#xff1a; 取消双击shift之后&#xff0c;如果想再次使用全局搜索&#xff0c;可以通过&#xff1a; ctrlshifA

Vue与relation-graph:高效打造关系图的秘诀

产品提需求啦&#xff0c;有一个需求就是实现一个功能&#xff1a;展现各个文件之间的调用关系&#xff0c;通过关系图的形式进行展示出来。 之前考虑使用antv x6实现此功能&#xff0c;但是考虑到只是展示的功能&#xff0c;也不需要进行交互&#xff0c;所以放弃使用antv x6&…

【操作系统笔记十二】Linux常用基础命令

Linux 常用快捷键 Tab 命令或路径等的补全键&#xff0c;特别常用的快捷键Ctrl insert 复制命令行内容&#xff08;常用可提高效率&#xff09;Shift insert 粘贴命令行内容&#xff08;常用可提高效率&#xff09;Ctrl C 中断当前任务&#xff08;退出&#xff09;Ctrl Z…

Java笔记:看清类加载过程

1 类加载的过程 1.1 加载 “加载”是“类加载”(Class Loading)过程的第一步。这个加载过程主要就是靠类器实现的&#xff0c;包括用户自定义类加载器。 加载的过程 在加载的过程中&#xff0c;JVM主要做3件事情 1&#xff09;通过一个类的全限定名来获取定义此类的二进制字节…

【Linux网络编程】日志与守护进程

日志是网络服务器程序在后台以守护进程的形式运行时&#xff0c;处理情况的描述被打印到了日志文件里面&#xff0c;方便维护人员查看。 1.前台进程与后台进程 左边会话输入命令 sleep 10000 & 代表进程后台运行&#xff0c;右边会话输入命令 sleep 20000可以看到命令行解…