SpringBoot 2 Redis 통합 읽 기와 쓰기 작업 실현
8800 단어 SpringBoot2Redis읽 기와 쓰기 동작
redis server 를 시작 합 니 다.아래 그림 에서 보 듯 이 포트 번호 6379:
2.프로젝트 실례
2.1 프로젝트 목록
프로젝트 디 렉 터 리 는 다음 그림 과 같다.
2.2 pom.xml
도입 의존:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.syrdbt</groupId>
<artifactId>redis-study</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>redis-study</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.3 자바 원본 파일시작 클래스,RedisStudy 응용 프로그램.java:
package com.syrdbt.redis.study;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RedisStudyApplication {
public static void main(String[] args) {
SpringApplication.run(RedisStudyApplication.class, args);
}
}
컨트롤 러,RedisStudyController.java:SpringBoot 에 내 장 된 Redis 와 의 도구 류:RedisTemplate;
SpringBoot 에는 RedisTemplate 외 에 도 StringRedisTemplate 가 내장 되 어 있 습 니 다.
StringRedisTemplate 는 key=String,value=String 의 키 값 만 조작 할 수 있 으 며,RedisTemplate 는 모든 종류의 key-value 키 값 을 조작 할 수 있 습 니 다.StringRedisTemplate 는 RedisTemplate 를 계승 했다.
package com.syrdbt.redis.study.controller;
import com.sun.tools.javac.code.Attribute;
import com.syrdbt.redis.study.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.Console;
/**
* @author syrdbt
*/
@RestController
public class RedisStudyController {
@Autowired
private RedisTemplate redisTemplate;
/**
* key
*/
@GetMapping("/redis/get")
public String visitStringByKey(@RequestParam String key) {
return (String) redisTemplate.opsForValue().get(Constant.NAMESPACE + ":" + key);
}
/**
* redis key/value
*/
@GetMapping("/redis/set")
public String visitStringByKey(@RequestParam String key, @RequestParam String value) {
try {
redisTemplate.opsForValue().set(Constant.NAMESPACE + ":" + key, value);
} catch (Exception e) {
return "error";
}
return "success";
}
}
redis 설정 클래스,RedisConfig.java:
package com.syrdbt.redis.study.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis
*
* @author syrdbt
*/
@Configuration
public class RedisConfig {
private final RedisTemplate redisTemplate;
@Autowired
public RedisConfig(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Bean
@SuppressWarnings("unchecked")
public RedisTemplate<String, Object> redisTemplate() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
RedisSerializer<Object> jsonString = new GenericToStringSerializer<>(Object.class);
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(jsonString);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(jsonString);
return redisTemplate;
}
}
상수 클래스 는 redis key 의 접두사 로 사 용 됩 니 다.Constant.자바:
package com.syrdbt.redis.study.constant;
/**
* @author syrdbt
* @date 2019-12-10
*/
public class Constant {
public static final String NAMESPACE = "REDIS-STUDY";
}
3.테스트쓰기 동작,접근http://localhost:8080/redis/set?key=name&value=syrdbt 。
읽 기 동작,접근http://localhost:8080/redis/get?key=name
4.문제
redis 의 기록 과 읽 기 를 통합 하 는 인 스 턴 스 가 완료 되 었 습 니 다.
하지만 두 가지 질문 이 더 있다.
4.567917.저 는 호스트 번호,포트 번호,사용자 이름,비밀 번 호 를 설정 하지 않 고 redis 를 방 문 했 습 니 다.분명히 SpringBoot 는 기본적으로 이런 것들 을 설 정 했 습 니 다.제 가 이 컴퓨터 의 redis 를 다운로드 한 후에 비밀 번 호 를 수정 하지 않 았 기 때문에 방문 할 수 있 습 니 다4.567917.정상 적 인 상황 에서 redisTmplate 를 직접 사용 하지 말고 도구 류 로 포장 하여 여러분 이 사용 하기에 편리 하도록 해 야 합 니 다스프링 부 트 2 통합 레 디 스 구현 읽 기와 쓰기 작업 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.스프링 부 트 2 레 디 스 읽 기와 쓰기 작업 내용 에 대해 서 는 이전 글 을 검색 하거나 아래 글 을 계속 읽 어 주시 기 바 랍 니 다.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
SpringBoot 2 Redis 통합 읽 기와 쓰기 작업 실현redis 설정 클래스,RedisConfig.java: 상수 클래스 는 redis key 의 접두사 로 사 용 됩 니 다.Constant.자바: 3.테스트 redis 의 기록 과 읽 기 를 통합 하 는 인 스 턴 스...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.