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


    这篇文章简单地介绍一下怎么在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客户端依赖

    1. <dependency>
    2. <groupId>redis.clientsgroupId>
    3. <artifactId>jedisartifactId>
    4. <version>4.3.1version>
    5. dependency>

    完整的pom.xml

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0modelVersion>
    6. <groupId>org.examplegroupId>
    7. <artifactId>redisartifactId>
    8. <version>1.0-SNAPSHOTversion>
    9. <properties>
    10. <maven.compiler.source>8maven.compiler.source>
    11. <maven.compiler.target>8maven.compiler.target>
    12. properties>
    13. <dependencies>
    14. <dependency>
    15. <groupId>redis.clientsgroupId>
    16. <artifactId>jedisartifactId>
    17. <version>4.3.1version>
    18. dependency>
    19. dependencies>
    20. project>

    jedis的案例代码

    1. package com.example.redis;
    2. import org.junit.jupiter.api.Test;
    3. import org.springframework.boot.test.context.SpringBootTest;
    4. import redis.clients.jedis.Jedis;
    5. import redis.clients.jedis.JedisPool;
    6. import java.util.HashMap;
    7. import java.util.Map;
    8. @SpringBootTest
    9. class RedisTests {
    10. @Test
    11. void contextLoads() {
    12. JedisPool pool = new JedisPool("192.168.254.128", 6379);
    13. try (Jedis jedis = pool.getResource()) {
    14. jedis.set("foo", "bar");
    15. System.out.println(jedis.get("foo"));
    16. Map hash = new HashMap<>();
    17. hash.put("name", "John");
    18. hash.put("surname", "Smith");
    19. hash.put("company", "Redis");
    20. hash.put("age", "29");
    21. jedis.hset("user-session:123", hash);
    22. System.out.println(jedis.hgetAll("user-session:123"));
    23. }
    24. }
    25. }

    关闭保护模式

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

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

    1. 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.
    2. at redis.clients.jedis.Protocol.processError(Protocol.java:96)
    3. at redis.clients.jedis.Protocol.process(Protocol.java:137)
    4. at redis.clients.jedis.Protocol.read(Protocol.java:192)
    5. at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:316)
    6. at redis.clients.jedis.Connection.getOne(Connection.java:298)
    7. at redis.clients.jedis.Connection.executeCommand(Connection.java:123)
    8. at redis.clients.jedis.Jedis.set(Jedis.java:4880)
    9. at com.example.redis.RedisTests.contextLoads(RedisTests.java:19)
    10. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    11. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    12. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    13. at java.lang.reflect.Method.invoke(Method.java:498)
    14. at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    15. at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    16. at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    17. at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    18. at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    19. at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    20. at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    21. at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    22. at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    23. at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    24. at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    25. at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    26. at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    27. at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    28. at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    29. at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    30. at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    31. at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    32. at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    33. at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    34. at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    35. at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    36. at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    37. at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    38. at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    39. at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    40. at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    41. at java.util.ArrayList.forEach(ArrayList.java:1257)
    42. at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    43. at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    44. at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    45. at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    46. at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    47. at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    48. at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    49. at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    50. at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    51. at java.util.ArrayList.forEach(ArrayList.java:1257)
    52. at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    53. at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    54. at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    55. at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    56. at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    57. at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    58. at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    59. at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    60. at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    61. at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    62. at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    63. at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    64. at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    65. at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    66. at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    67. at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    68. at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    69. at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    70. at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    71. at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    72. at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    73. at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
    74. 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...catch块的方式操作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的介绍就到这里了,看完不要忘了点赞+收藏哦~

  • 相关阅读:
    TypeScript常见面试题第十一节
    Linux--共享内存
    SpringBoot与MongoDB的集成使用
    如何让Java项目兼容更多的客户端设备(二)
    【C++】vector的介绍与使用
    docker镜像存储在哪里
    【若依(ruoyi)】Java---如何在Apifox上传params参数--延伸--如何在Apifox上传Map类型参数
    golang基础 :waitgroup用法及使用要点
    [PyQt] Pycharm 配置 PyQt 开发环境
    性能测试-基础理论知识
  • 原文地址:https://blog.csdn.net/heyl163_/article/details/132981470