redis<二>spring使用redis,配置远程登录和密码

news2024/7/4 6:33:08

使用默认的redis配置

  1. 改pom, 加入redis依赖,版本可以不需要写,由spring的父工程控制。
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<!--整合redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

  1. 配配置类
package com.fuzekun.demo1.configuration;

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.RedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // 设置value的序列化方式
        template.setValueSerializer(RedisSerializer.json());
        // 设置hash的key的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置hash的value的序列化方式
        template.setHashValueSerializer(RedisSerializer.json());

        template.afterPropertiesSet();
        return template;
    }

}

  1. 写测试类
package com.fuzekun.demo1.utils;

import com.fuzekun.demo1.Demo1Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = Demo1Application.class)
public class RedisTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testStrings() {
        String redisKey = "test:count";

        redisTemplate.opsForValue().set(redisKey, 1);

        System.out.println(redisTemplate.opsForValue().get(redisKey));
        System.out.println(redisTemplate.opsForValue().increment(redisKey));
        System.out.println(redisTemplate.opsForValue().decrement(redisKey));
    }

    @Test
    public void testHashes() {
        String redisKey = "test:user";

        redisTemplate.opsForHash().put(redisKey, "id", 1);
        redisTemplate.opsForHash().put(redisKey, "username", "zhangsan");

        System.out.println(redisTemplate.opsForHash().get(redisKey, "id"));
        System.out.println(redisTemplate.opsForHash().get(redisKey, "username"));
    }

    @Test
    public void testLists() {
        String redisKey = "test:ids";

        redisTemplate.opsForList().leftPush(redisKey, 101);
        redisTemplate.opsForList().leftPush(redisKey, 102);
        redisTemplate.opsForList().leftPush(redisKey, 103);

        System.out.println(redisTemplate.opsForList().size(redisKey));
        System.out.println(redisTemplate.opsForList().index(redisKey, 0));
        System.out.println(redisTemplate.opsForList().range(redisKey, 0, 2));

        System.out.println(redisTemplate.opsForList().leftPop(redisKey));
        System.out.println(redisTemplate.opsForList().leftPop(redisKey));
        System.out.println(redisTemplate.opsForList().leftPop(redisKey));
    }

    @Test
    public void testSets() {
        String redisKey = "test:teachers";

        redisTemplate.opsForSet().add(redisKey, "刘备", "关羽", "张飞", "赵云", "诸葛亮");

        System.out.println(redisTemplate.opsForSet().size(redisKey));
        System.out.println(redisTemplate.opsForSet().pop(redisKey));
        System.out.println(redisTemplate.opsForSet().members(redisKey));
    }

    @Test
    public void testSortedSets() {
        String redisKey = "test:students";

        redisTemplate.opsForZSet().add(redisKey, "唐僧", 80);
        redisTemplate.opsForZSet().add(redisKey, "悟空", 90);
        redisTemplate.opsForZSet().add(redisKey, "八戒", 50);
        redisTemplate.opsForZSet().add(redisKey, "沙僧", 70);
        redisTemplate.opsForZSet().add(redisKey, "白龙马", 60);

        System.out.println(redisTemplate.opsForZSet().zCard(redisKey));
        System.out.println(redisTemplate.opsForZSet().score(redisKey, "八戒"));
        System.out.println(redisTemplate.opsForZSet().reverseRank(redisKey, "八戒"));
        System.out.println(redisTemplate.opsForZSet().reverseRange(redisKey, 0, 2));
    }

    @Test
    public void testKeys() {
        redisTemplate.delete("test:user");

        System.out.println(redisTemplate.hasKey("test:user"));

        redisTemplate.expire("test:students", 10, TimeUnit.SECONDS);
    }

    // 多次访问同一个key
    @Test
    public void testBoundOperations() {
        String redisKey = "test:count";
        BoundValueOperations operations = redisTemplate.boundValueOps(redisKey);
        operations.increment();
        operations.increment();
        operations.increment();
        operations.increment();
        operations.increment();
        System.out.println(operations.get());
    }

    // 编程式事务
    @Test
    public void testTransactional() {
        Object obj = redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String redisKey = "test:tx";

                operations.multi();

                operations.opsForSet().add(redisKey, "zhangsan");
                operations.opsForSet().add(redisKey, "lisi");
                operations.opsForSet().add(redisKey, "wangwu");

                System.out.println(operations.opsForSet().members(redisKey));

                return operations.exec();
            }
        });
        System.out.println(obj);
    }

}

运行结果

在这里插入图片描述

自己定义RedisconnectionFactory

用来配置登录的地址和登录的端口以及登录密码

创建RedisConnectionFactory,由他创建RedisConnection。这个工厂会被直接注入到redisTemplate

官方文档上说使用工厂创建的连接线程安全,并且可以被实例共享。那么就是说,是线程安全的单例模式(个人猜测)。

  1. 导入jedis依赖
<dependencies>

  <!-- other dependency elements omitted -->

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

</dependencies>
  1. 编写配置类,获取连接工厂
@Configuration
class RedisConfiguration {

  @Bean
  public JedisConnectionFactory redisConnectionFactory() {
															// 设置域名和端口
    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("server", 6379);
    config.setPassword("fdafda");							// 设置密码
    return new JedisConnectionFactory(config);
  }
}
  1. 将工厂创建的连接注入到模板配置中。仍旧是上面的配置类
package com.fuzekun.demo1.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {


    /**
     * Jedis
     */
//    @Bean
//    public RedisConnectionFactory jedisConnectionFactory() {
//        RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
//                .sentinel("node0", 6379);
//        sentinelConfig.setPassword("1230");
//        return new JedisConnectionFactory(sentinelConfig);
//    }

    // 创建工厂,配置端口,账号,密码
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("node0", 6379);
        config.setPassword("1230");
        return new JedisConnectionFactory(config);
    }
    // 将工厂注入到factory中
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // 设置value的序列化方式
        template.setValueSerializer(RedisSerializer.json());
        // 设置hash的key的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置hash的value的序列化方式
        template.setHashValueSerializer(RedisSerializer.json());

        template.afterPropertiesSet();
        return template;
    }

}

关于工厂模式的思考:

为什么要用工厂模式?

  1. 控制对象创建的工序,方便对象的管理。
  2. 将对象和控制解耦,增加了灵活性,方便对象类的扩展。
  3. 使用配置文件,解决了对象的选择问题。

为什么使用抽象工厂模式? 定义了产品一族。

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

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

相关文章

Spring Bean基础-4

1. 定义Bean: 什么是BeanDefinition? 什么是BeanDefinition?BeanDefinition 是 Spring Framework 中定义 Bean 的配置元信息接口, 包含: Bean 的类名Bean 行为配置元素, 如作用域、自动绑定的模式、生命周期回调等其他 Bean 引用, 又可称作合作者 (Collaborators) 或者依赖 …

Feign的简介及使用

一、Feign简介 Feign是一个声明式的http客户端&#xff0c;官方地址:https://github.com/OpenFeign/feign 其作用就是帮助我们优雅的实现http请求的发送&#xff0c;解决代码可读性差&#xff0c;编程体验不统一、参数复杂URL难以维护的问题。 二、使用Feign的步骤 1.引入依赖…

网络原理(Java网络编程)

1.局域网和广域网 局域网LAN: 即 Local Area Network,简称LAN. 局域网内的主机之间能方便的进行网络通信,又称为内网;局域网和局域网之间在没有连接的情况下,是无法通信的.局域网一般可以由交换机或路由器组建. 广域网WAN: 即 Wide Area Network,简称WAN. 广域网是将多个局域网…

【28-业务开发-基础业务-属性管理-SKU和SPU基本概念-SKU和SPU关联关系-属性实体之间的关联关系-批量菜单创建】

一.知识回顾 【0.三高商城系统的专题专栏都帮你整理好了&#xff0c;请点击这里&#xff01;】 【1-系统架构演进过程】 【2-微服务系统架构需求】 【3-高性能、高并发、高可用的三高商城系统项目介绍】 【4-Linux云服务器上安装Docker】 【5-Docker安装部署MySQL和Redis服务】…

力扣(LeetCode)32. 最长有效括号(C++)

栈模拟 合法的括号序列满足两条性质&#xff1a; 1.左括号数等于右括号数 2.任意前缀里&#xff0c;左括号数大于等于右括号数。 括号匹配和栈很般配&#xff0c;遇到左括号&#xff0c;下标入栈&#xff0c;遇到右括号&#xff0c;弹栈匹配。 这题的前缀里有两种不合法&…

【LSTM回归预测】attention机制LSTM时间序列回归预测【含Matlab源码 1992期】

⛄一、attention机制LSTM预测 1 总体框架 数字货币预测模型分为两部分&#xff0c;由LSTM模块和Attention模块组成。 2 LSTM模块 长短期记忆网络&#xff08;LSTM&#xff09;是一种特殊的递归神经网络&#xff08;RNN&#xff09;模型&#xff0c;是为了解决RNN模型梯度消失…

【Codeforces Round #835 (Div. 4)】A——G题解

文章目录A Medium Number题意思路代码B Atillas Favorite Problem题意思路代码C Advantage题意思路代码D Challenging Valleys题意思路代码E Binary Inversions题意思路代码F Quests题意思路代码G SlavicGs Favorite Problem题意思路代码A Medium Number 题意 三个数&#xf…

窗口-视口转换(详细)

在QPainter中&#xff0c;绘制图像使用逻辑坐标绘制&#xff0c;然后再转化为绘图设备的物理坐标。 窗口&#xff08;window&#xff09;&#xff1a;表示逻辑坐标下的相同矩形视口&#xff08;viewport&#xff09;&#xff1a;表示物理坐标下的指定的一个任意矩形默认情况&am…

中国互联网大会天翼云展区大揭秘!

11月15日&#xff0c;由工业和信息化部、深圳市人民政府主办&#xff0c;中国互联网协会、广东省通信管理局、深圳市工业和信息化局等单位承办的2022&#xff08;第二十一届&#xff09;中国互联网大会在深圳开幕。本届大会以“发展数字经济 促进数字文明”为主题&#xff0c;聚…

单商户商城系统功能拆解34—应用中心—分销应用

单商户商城系统&#xff0c;也称为B2C自营电商模式单店商城系统。可以快速帮助个人、机构和企业搭建自己的私域交易线上商城。 单商户商城系统完美契合私域流量变现闭环交易使用。通常拥有丰富的营销玩法&#xff0c;例如拼团&#xff0c;秒杀&#xff0c;砍价&#xff0c;包邮…

在IDEA中搭建Spring5.2.x版本源码(~附带完整过程和图示~)

1.开发环境 JDK8IntelliJ IDEA 2019.1.4 gradle 5.6.4git 2.33.0 2.操作步骤 下载并安装git 进入https://git-scm.com/downloads&#xff0c;下载对应操作系统的git版本一直点击next安装即可记得配置环境变量 获取Spring源码 使用clone的方式将源码拉取到本地&#xff0c;方便…

Java递归查询树形结构(详解)

一.数据准备 数据库表结构如下所示&#xff0c; INSERT INTO jg_user.com_type(type_id, parent_id, type_name) VALUES (1, 0, 合伙企业); INSERT INTO jg_user.com_type(type_id, parent_id, type_name) VALUES (2, 0, 有限公司); INSERT INTO jg_user.com_type(type_id, p…

力扣(LeetCode)878. 第 N 个神奇数字(C++)

二分查找数论 数论知识——辗转相除法、容斥原理。 辗转相除求最大公约数&#xff0c;两数相乘除以最大公约数&#xff0c;就是最小公倍数。 容斥原理求最多不重复元素&#xff0c;最大不重复面积。 <小学数奥> 从数据范围里&#xff0c;用容斥原理找 a/ba/ba/b 的倍数个…

Pytorch 下 TensorboardX 使用

这里引用一下在其他地方看到的一些话&#xff1a; tensorboard做为Tensorflow中强大的可视化工具&#xff0c;已经被普遍使用。 但针对其余框架&#xff0c;例如Pytorch&#xff0c;以前一直没有这么好的可视化工具可用&#xff0c;PyTorch框架自己的可视化工具是Visdom&…

实验九 数据微积分与方程数值求解(matlab)

实验九 数据微积分与方程数值求解 1.1实验目的 1.2实验内容 1.3流程图 1.4程序清单 1.5运行结果及分析 1.6实验的收获与体会 1.1实验目的 1&#xff0c;掌握求数值导数和数值积分的方法&#xff1b; 2&#xff0c;掌握代数方程数组求解的方法&#xff1b; 3&a…

【Mysql】Centos 7.6安装Mysql8

这里centos为阿里云默认镜像。 一、卸载历史历史版本 1、检查是否有服务启动 # service mysqld status 2、停止mysql服务 # service mysqld stop 3、查看mysql历史安装组件 # rpm -qa|grep mysqlmysql-libs-5.1.71-1.el6.x86_64 4、卸载组件 # rpm -e --nodeps mysql…

2022世界VR产业大会圆满收官,酷雷曼惊艳亮相!

11月14日&#xff0c;由工业和信息化部、江西省人民政府联合主办的全球VR领域规模最大、规格最高、影响最广的年度盛会——2022世界VR产业大会在江西南昌圆满落下帷幕。 本次大会得到了党中央、国务院的高度重视&#xff0c;国务委员王勇出席大会开幕式并讲话&#xff1b;大会邀…

【转】DNS隧道检测特征

原文链接&#xff1a;DNS隧道检测特征总结 - 知乎 一、摘要 企业内网环境中&#xff0c;DNS协议是必不可少的网络通信协议之一&#xff0c;为了访问互联网和内网资源&#xff0c;DNS提供域名解析服务&#xff0c;将域名和IP地址进行转换。网络设备和边界防护设备在一般的情况…

C++:内存管理:C++内存管理详解

C语言内存管理是指&#xff1a;对系统的分配、创建、使用这一系列操作。在内存管理中&#xff0c;由于是操作系统内存&#xff0c;使用不当会造成很麻烦的后果。本文将从系统内存的分配、创建出发&#xff0c;并且结合例子来说明内存管理不当会造成的结果以及解决方案。 一&am…

【Spring】Spring AOP的实现原理

目录 什么是AOP AOP的作用 AOP的优点 AOP框架 Spring AOP AspectJ 术语 1.Target ——目标类 2.Joinpoint ——连接点 3.Pointcut——切入点 4.Advice——通知/增强 5.Weaving——植入 6.Proxy——代理类 7.Aspect——切面 底层逻辑 开发流程 1.导入依…