锋盈数科-知识库 Logo
首页
软件开发
计算机基础
Hello Halo
新手必读
关于本知识库
登录 →
锋盈数科-知识库 Logo
首页 软件开发 计算机基础 Hello Halo 新手必读 关于本知识库
登录
  1. 首页
  2. 软件开发
  3. Java整合spring和springboot访问redis

Java整合spring和springboot访问redis

0
  • 软件开发
  • 发布于 2024-08-19
  • 0 次阅读
黄健
黄健

Java程序访问Redis

采用jedis API进行访问即可

  1. 关闭RedisServer端的防火墙

    systemctl stop firewalld(默认)
    systemctl disable firewalld.service(设置开启不启动)
    
  2. 新建maven项目后导入Jedis包
    pom.xml

    <dependency>
    	<groupId>redis.clients</groupId>
    	<artifactId>jedis</artifactId>
    	<version>2.9.0</version>
    </dependency>
    
  3. 写程序

    @Test
    public void testConn(){
         
    	//与Redis建立连接 IP+port
    	Jedis redis = new Jedis("192.168.127.128", 6379);
    	//在Redis中写字符串 key value
    	redis.set("jedis:name:1","jd-zhangfei");
    	//获得Redis中字符串的值
    	System.out.println(redis.get("jedis:name:1"));
    	//在Redis中写list
    	redis.lpush("jedis:list:1","1","2","3","4","5");
    	//获得list的长度
    	System.out.println(redis.llen("jedis:list:1"));
    }
    

Spring访问Redis

  1. 创建spring工程后引入相关的依赖
    <properties>
        <spring.version>5.2.14.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>2.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <testSource>11</testSource>
                    <testTarget>11</testTarget>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
  1. 创建spring配置文件和redis配置文件
    首先是spring配置文件 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="classpath*:redis.properties"></context:property-placeholder>

    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"></property>
        <property name="maxTotal" value="${redis.maxTotal}"></property>
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
        <property name="testOnBorrow" value="${redis.testOnBorrow}" ></property>
    </bean>

    <bean id="redisConfiguration" class="org.springframework.data.redis.connection.RedisStandaloneConfiguration">
        <property name="hostName" value="${redis.host}"></property>
        <property name="port" value="${redis.port}"></property>
    </bean>

    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <constructor-arg ref="redisConfiguration"></constructor-arg>
        <property name="timeout" value="${redis.timeout}"></property>
        <property name="poolConfig" ref="jedisPoolConfig"></property>
    </bean>
    
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"></property>
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer">
            </bean>
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        </property>
    </bean>

</beans>

然后是redis客户端的配置文件redis.properties

redis.maxTotal=10
redis.maxIdle=5
redis.maxWaitMillis=20000
redis.testOnBorrow=false
redis.host=192.168.31.10
redis.port=6379
redis.timeout=50000

3. 创建测试类

/**
 * @author Elvis
 * @create 2021-08-08 22:47
 */

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;

/**
 * @program: redis-study
 * @Description
 * @author Elvis
 * @date 2021-08-08 22:47    
 */
public class RedisTest {
   

    ClassPathXmlApplicationContext applicationContext = null;
    RedisTemplate<Serializable, Serializable> redisTemplate = null;

    @Before
    public void before() {
   
        applicationContext = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
        redisTemplate = (RedisTemplate) applicationContext.getBean("redisTemplate");

    }

    @Test
    public void test1() {
   
        redisTemplate.opsForValue().set("name", "zhaoyun");
    }

    @Test
    public void test2() {
   
        String name = (String) redisTemplate.opsForValue().get("name");
        System.out.println(name);
    }

}

先执行插入,再执行查询

SpringBoot访问Redis

  1. 新建工程后添加pom依赖

        <parent>
            <artifactId>spring-boot-starter-parent</artifactId>
            <groupId>org.springframework.boot</groupId>
            <version>2.4.2</version>
        </parent>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-test</artifactId>
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                    <configuration>
                        <source>11</source>
                        <target>11</target>
                        <testSource>11</testSource>
                        <testTarget>11</testTarget>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
  2. 添加配置文件application.yml

    spring:
      redis:
        host: 192.168.31.10
        port: 6379
        jedis:
          pool:
            max-active: 8
            max-idle: 1
            max-wait: 20000
        client-type: jedis
    
  3. 添加配置类RedisConfig

    package com.elvis.config;
    /**
     * @author Elvis
     * @create 2021-08-09 7:43
     */
    
    import org.springframework.beans.factory.annotation.Autowired;
    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.StringRedisSerializer;
    
    /**
     * @program: redis-study
     * @Description
     * @author Elvis
     * @date 2021-08-09 7:43    
     */
    @Configuration
    public class RedisConfig {
         
    
        @Autowired
        RedisConnectionFactory connectionFactory;
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
         
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setValueSerializer(new StringRedisSerializer());
            redisTemplate.setStringSerializer(new StringRedisSerializer());
            redisTemplate.setHashValueSerializer(new StringRedisSerializer());
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setConnectionFactory(connectionFactory);
            return redisTemplate;
        }
    }
    
    
  4. 添加RedisController

    package com.elvis.controller;
    /**
     * @author Elvis
     * @create 2021-08-09 7:48
     */
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @program: redis-study
     * @Description
     * @author Elvis
     * @date 2021-08-09 7:48    
     */
    @RestController
    @RequestMapping("/redis")
    public class RedisController {
         
    
        @Autowired
        RedisTemplate<String, Object> redisTemplate;
    
        @RequestMapping("/put")
        public String put(@RequestParam(required = true) String key,
                          @RequestParam(required = true) String value) {
         
            redisTemplate.opsForValue().set(key, value);
            return "success";
        }
    
        @RequestMapping("/get")
        public String get(@RequestParam(required = true) String key) {
         
            Object o = redisTemplate.opsForValue().get(key);
            return (String) o;
        }
    }
    
    
  5. 修改Application并运行

    package com.elvis;
    /**
     * @author Elvis
     * @create 2021-08-09 8:08
     */
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    
    /**
     * @program: redis-study
     * @Description
     * @author Elvis
     * @date 2021-08-09 8:08    
     */
    @SpringBootApplication
    @EnableCaching
    public class RunBoot {
         
        public static void main(String[] args) {
         
            SpringApplication.run(RunBoot.class, args);
        }
    }
    
    


原文链接: https://blog.csdn.net/Kiven_ch/article/details/119548254

标签: #redis 48 #软件开发 1171 #JAVA 991
相关文章

万字:支付“核心系统”详解 2024-11-02 15:33

专栏作者:隐墨星辰 \| 主编:陈天宇宙 这篇文章也尝试化繁为简,探寻支付系统的本质,讲清楚在线支付系统最核心的一些概念和设计理念。 虽然支付行业已经过了风头最劲的时光,但跨境支付仍然在蓬勃发展,每年依然有很多新人进入这个行业,这篇文章尝试为这些刚入行的新人提供一点帮助。 文章只介绍一些支付行业十几

资深支付架构师视角:实战从问题定义到代码落地的完整套路 2024-11-02 15:33

前言 今天从一个实际案例入手,介绍站在架构师的角度,如何识别并定义问题,提炼需求,技术方案选型,再到详细设计,最后利用AI的能力协助写出核心的代码,验证与调优。 解决问题存在一定的模式,也可以称之为框架,总结出自己的思考和解题框架,以后再碰到同类型的问题就可以如庖丁解牛一样容易。 很多年前,我写代码

Spring 实现 3 种异步接口 2024-10-18 09:07

大家好,我是苏三~ 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable、WebAsyncTask 和 DeferredResult、CompletableFuture等均可实现。 但这些方法有局限性,处理结果仅返回单个值。在某些场景下,如果需要接口异步处理的同时,还持续不断地

重学SpringBoot3-集成Redis(五)之布隆过滤器 2024-10-08 11:24

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》 期待您的点赞👍收藏⭐评论✍ 重学SpringBoot3-集成Redis(五)之布隆过滤器 1. 什么是布隆过滤器? * 基本概念 适用场景 2. 使用 Redis 实现布隆过滤器 * 项目依赖 Redis 配置

设计模式第16讲——迭代器模式(Iterator) 2024-10-08 11:24

一、什么是迭代器模式 迭代器模式是一种行为型设计模式,它提供了一种统一的方式来访问集合对象中的元素,而不是暴露集合内部的表示方式。简单地说,就是将遍历集合的责任封装到一个单独的对象中,我们可以按照特定的方式访问集合中的元素。 二、角色组成 抽象迭代器(Iterator):定义了遍历聚合对象所需的方法

vue2路由和vue3路由区别及原理 2024-10-08 11:24

一、Vue2 与 Vue3 路由的区别 1. 创建路由实例方式的不同 Vue 2 中,通过 Vue.use() 注册路由插件,并通过 new VueRouter() 来创建路由实例。 import Vue from 'vue';import VueRouter from 'vue-router';i

目录

IT 外包服务商

  • 意见投递
  • zyf6619

软件开发应用

主菜单

  • 首页
  • 软件开发
  • 计算机基础
  • Hello Halo
  • 新手必读
  • 关于本知识库
Copyright © 2024 your company All Rights Reserved. Powered by Halo.