springboot 에서 redis 를 사용 하 는 방법 코드 상세 설명

8864 단어 springbootredis
특별 설명:
본 고 는 새로운 spring boot 2.1.3 을 대상 으로 spring data 의존 spring-boot-starter-data-redis이 고 기본 연결 탱크 는 lettuce 입 니 다.
redis 는 고성능 메모리 데이터베이스 로 서 사용 하지 않 으 면 너무 시대 에 뒤떨어 집 니 다.이전에 node.js 에서 redis 를 사용 한 적 이 있 습 니 다.이 기록 은 어떻게 redis 를 spring boot 에 통합 하 는 지 기록 합 니 다.redis 작업 클래스 를 제공 하고 주 해 는 redis 두 가지 방식 을 사용 합 니 다.주요 내용 은 다음 과 같다.
•docker 설치 redis
•springboot 통합 redis
•redis 작업 클래스 작성
•주 해 를 통 해 redis 사용
설치 redis
docker 설 치 를 통 해 docker copose 는 다음 과 같이 파일 을 편성 합 니 다.

# docker-compose.yml
version: "2"
services:
 redis:
 container_name: redis
 image: redis:3.2.10
 ports:
  - "6379:6379"
그리고docker-compose.yml이 있 는 디 렉 터 리 에서docker-compose up -d명령 을 사용 하여 redis 를 시작 합 니 다. 
통합 springboot
설명:springboot 버 전 2.1.3
maven 의존 도 추가
spring-boot-starter-data-redis 의존 만 추가 하면 됩 니 다.lettuce 의존 을 제거 하고 jedis 와 jedis 의존 comons-pool 2 를 도입 합 니 다.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis</artifactId>
 <exclusions>
  <exclusion>
   <groupId>io.lettuce</groupId>
   <artifactId>lettuce-core</artifactId>
  </exclusion>
 </exclusions>
</dependency>

<dependency>
 <groupId>org.apache.commons</groupId>
 <artifactId>commons-pool2</artifactId>
</dependency>

<dependency>
 <groupId>redis.clients</groupId>
 <artifactId>jedis</artifactId>
</dependency>
springboot 프로필 작성
프로필 은 다음 과 같 습 니 다:

server:
 port: 8081
 servlet:
 context-path: /sso
spring:
 application:
 name: SSO
 cache:
 type: redis
 redis:
 database: 0
 host: 192.168.226.5
 port: 6379
 #       ,      
 password:
 #       (ms)
 timeout: 1000ms
 #    springboot   jedis  lettuce
 jedis:
  pool:
  #         (       )
  max-active: 8
  #            (     )
  max-wait: 5000ms
  #        
  max-idle: 8
  #        
  min-idle: 0
설정 클래스 작성
설정 클래스 코드 는 다음 과 같 습 니 다:

@EnableCaching//    
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
 /**
  *        ,             
  *
  * @param connectionFactory    
  * @return
  */
 @Bean
 public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
  RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
    .defaultCacheConfig()
    .entryTtl(Duration.ofSeconds(60));
  //  :     new     ,     entryTtl        
  //        ,     .entryTtl             ,              

  RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
  RedisCacheManager manager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
  return manager;
 }
 @SuppressWarnings("all")
 @Bean
 public RedisTemplate<String, String> redisTemplate(JedisConnectionFactory factory) {
  StringRedisTemplate template = new StringRedisTemplate(factory);
  Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  ObjectMapper om = new ObjectMapper();
  om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  jackson2JsonRedisSerializer.setObjectMapper(om);
  RedisSerializer stringSerializer = new StringRedisSerializer();
  template.setKeySerializer(stringSerializer);
  template.setValueSerializer(jackson2JsonRedisSerializer);
  template.setHashKeySerializer(stringSerializer);
  template.setHashValueSerializer(jackson2JsonRedisSerializer);
  template.afterPropertiesSet();
  return template;
 }

 //  jedis     jedis    
 @Bean
 public JedisConnectionFactory jedisConnectionFactory() {
  logger.info("jedisConnectionFactory:    ");
  JedisPoolConfig config = new JedisPoolConfig();
  config.setMaxIdle(maxIdle);
  config.setMinIdle(minIdle);
  config.setMaxWaitMillis(maxWaitMillis);
  config.setMaxTotal(maxActive);
  //         ,  true
  config.setBlockWhenExhausted(true);
  //    pool jmx    ,  true
  config.setJmxEnabled(true);
  JedisConnectionFactory factory = new JedisConnectionFactory();
  factory.setPoolConfig(config);
  factory.setHostName(host);
  factory.setPort(port);
  factory.setPassword(password);
  factory.setDatabase(database);
  factory.setTimeout(timeout);
  return factory;
 }
}
사용 방법
캐 시 작업 을 하 는 방법 은 두 가지 가 있 습 니 다.하 나 는 캐 시 주 해 를 추가 하여 여러 가지 작업 을 하 는 것 입 니 다.하 나 는 수 동 제어 입 니 다.개인 적 으로 수 동 통 제 를 좋아 하 는데 이것 은 모두 자신의 통제 에 있다 고 생각한다.
주 해 를 통 해 사용 하 다
주로 다음 과 같은 5 개의 주해 가 있다.
•@CacheConfig:클래스 캐 시,캐 시 키 접두사 설정 등
•@Cacheable:캐 시 입 구 를 터치 합 니 다.
•@CacheEvict:캐 시 제거 트리거
•@CachePut:캐 시 업데이트
•@Caching:조합 캐 시
@CacheConfig
이 주 해 는 캐 시 를 분류 할 수 있 습 니 다.클래스 급 주해 입 니 다.주로 특정한 종류의 캐 시 전역 설정 에 사 용 됩 니 다.예 는 다음 과 같 습 니 다.

@CacheConfig(cacheNames = "redis_test")
@Service
public class RedisService {
 //....
}
위의 CacheConfig 는 클래스 아래 주 해 를 통 해 생 성 된 key 에redis_test 접 두 사 를 붙 입 니 다.
@Cacheable
방법 단계 주석,key 에 따라 캐 시 조회:
•key 가 존재 하지 않 는 다 면,방법 을 redis 에 되 돌려 줍 니 다.
•키 가 존재 하면 캐 시 에서 직접 값 을 가 져 옵 니 다.
 예 는 다음 과 같다.

 /**
  *     ,          ,key           .
  *     key,     key        key
  * @return long
  */
 @Cacheable(key = "'currentTime'")
 public long getTime() {
  return System.currentTimeMillis();
 }
이 코드 를 여러 번 호출 하면 매번 돌아 오 는 값 이 같 음 을 발견 할 수 있 습 니 다.
CachePut
캐 시 업데이트 에 사용 되 며,호출 할 때마다 db 요청,캐 시 데 이 터 를 생각 합 니 다.
•키 가 존재 한다 면 내용 업데이트
•키 가 존재 하지 않 으 면 내용 삽입
코드 는 다음 과 같 습 니 다:

/**
  *            ,      db
  */
 @CachePut(key = "'currentTime'+#id")
 public long updateTime(String id) {
  return System.currentTimeMillis();
 }
이 방법 을 호출 할 때마다 key 에 따라 redis 의 캐 시 데 이 터 를 새로 고 칩 니 다.
@CacheEvict
키 에 따라 캐 시 에 있 는 데 이 터 를 삭제 합 니 다.allEntries=true 캐 시 에 있 는 모든 데 이 터 를 삭제 하 는 것 을 표시 합 니 다.
 코드 는 다음 과 같 습 니 다:

 @CacheEvict(key = "'currentTime'+#id",allEntries=false)
 public void deleteTime(String id) {
 }
@Caching
이 주 해 는 다른 주 해 를 조합 하여 사용 할 수 있다.예 를 들 어 다음 의 예:

//value   key    
 @Caching(put = {@CachePut(value = "user", key = "'name_'+#user.name"),
   @CachePut(value = "user", key = "'pass_'+#user.password")})
 public User testCaching(User user) {
  return user;
 }
위의 코드 가 실 행 된 후 redis 에 두 개의 기록 을 삽입 합 니 다.사용keys *하면 다음 과 같은 결 과 를 볼 수 있 습 니 다.

수 동 제어
수 동 제 어 는 mybatis 의 핸드폰 sql 문장 에 해당 하 며,캐 시 조회,캐 시 업데이트,캐 시 삭제 등 여러 가지 방법 을 호출 해 야 합 니 다.
사용 방법 은 util/RedisUtil 의 방법 을 참조 합 니 다.redisTemplate기본적으로 모든 redis 작업 을 실현 할 수 있다.
프로젝트 원본 코드
총결산
위 에서 말 한 것 은 소 편 이 소개 한 springboot 에서 redis 를 사용 하 는 방법 코드 에 대한 상세 한 설명 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.소 편 은 제때에 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
만약 당신 이 본문 이 당신 에 게 도움 이 된다 고 생각한다 면,전 재 를 환영 합 니 다.번 거 로 우 시 겠 지만 출처 를 밝 혀 주 십시오.감사합니다!

좋은 웹페이지 즐겨찾기