SpringCloud集成Spring Data Redis

文章目录

  • Spring Data Redis
  • 源码
    • springcloud-parent2父Maven模块
    • spring-redis子Maven模块
  • 结果
  • 分析

Spring Data Redis

  如同使用SpringData进行关系型数据库访问一样,使用Spring Data Redis的第一步就是连接到Redis服务器。要想实现连接,就需要获取RedisConnection,而获取RedisConnection的手段是使用RedisConnectionFactory接口。Spring Data Redis对Redis操作做了封装,提供了一个工具类RedisTemplate,通过注入RedisConnectionFactory到RedisTemplate中,该RedisTemplate就能获取RedisConnection。

  RedisTemplate提供了丰富的接口来操作Redis的特定数据类型,这些接口包括ValueOperations、ListOperations、SetOperations、ZSetOperations和HashOperations等,分别对应Redis中的String、List、Set、ZSet和Hash 5种常见的数据结构。

  SpringCloud在集成Spring Data Redis时,需要引入spring-boot-starter-data-redis依赖。

源码

springcloud-parent2父Maven模块

  pom.xml




  4.0.0
  pom
  
    spring-data
    spring-redis
  

  
    org.springframework.boot
    spring-boot-starter-parent
    1.5.4.RELEASE
  

  com.lyc
  springcloud-parent2
  1.0-SNAPSHOT

  springcloud-parent2

  
  
    
      
        org.springframework.cloud
        spring-cloud-dependencies
        Dalston.SR3
        pom
        import
      
    
  

  
    
      org.springframework.boot
      spring-boot-starter-web
    
    
    
      org.projectlombok
      lombok
      1.18.4
    
  


spring-redis子Maven模块

  pom.xml




    
        springcloud-parent2
        com.lyc
        1.0-SNAPSHOT
    
    4.0.0

    spring-redis

    spring-redis

    
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
    


  SpringRedisApplication启动类

package com.lyc.pringRedis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/** * @author: zhangzhenyi * @date: 2019/3/10 14:34 * @description: SpringRedis启动类 **/
@SpringBootApplication
public class SpringRedisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringRedisApplication.class,args);
    }

    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){

        RedisTemplate<Object,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        @SuppressWarnings("unchecked")
        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);

        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setKeySerializer(new StringRedisSerializer());
        return template;
    }
}

  PersonRedisController类

package com.lyc.pringRedis.controller;

import com.lyc.pringRedis.entity.Person;
import com.lyc.pringRedis.server.PersonRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** * @author: zhangzhenyi * @date: 2019/3/10 14:41 * @description: PersonRedis Controller **/
@RestController
public class PersonRedisController {

    @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
    @Autowired
    PersonRedisRepository personRedisRepository;

    /** * 在Redis中存值 */
    @RequestMapping("/setPerson")
    public void setPerson(){
        Person person = Person.builder()
                .id(1L)
                .name("zhangsan")
                .age(32)
                .address("shanghai")
                .build();
        personRedisRepository.save(person);
    }

    /** * 读取存入Redis中的值 * @return */
    @RequestMapping("/getPerson")
    public Person getPerson(){
        return personRedisRepository.getPerson();
    }

}

  PersonRedisRepository类

package com.lyc.pringRedis.server;

import com.lyc.pringRedis.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/** * @author: zhangzhenyi * @date: 2019/3/10 14:29 * @description: PersonRedis Repository **/
@Repository
public class PersonRedisRepository {

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    @SuppressWarnings({"SpringJavaInjectionPointsAutowiringInspection", "WeakerAccess"})
    @Resource(name = "redisTemplate")
    ValueOperations<Object,Object> valueOperations;

    public void save(Person person){
        valueOperations.set(person.getId().toString(),person);
    }

    public Person getPerson(){
        return (Person) valueOperations.get("1");
    }

}

  Person类

package com.lyc.pringRedis.entity;

import lombok.*;

/** * @author: zhangzhenyi * @date: 2019/3/10 11:02 * @description: Person实体类 **/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Person {

    private Long id;       //主键id
    private String name;    //姓名
    private Integer age;    //年龄
    private String address;    //地址

}

结果

  先访问:

http://localhost:8080/setPerson

  再访问:

http://localhost:8080/getPerson

  得到的结果如下:

SpringCloud集成Spring Data Redis_第1张图片

  该结果在Redis客户端中的访问结果如下:

SpringCloud集成Spring Data Redis_第2张图片

分析

  在Spring Data Redis中的Repository类需要注入Redis Template,并提供ValueOperations进行具体的操作,如在PersonRedisRepository类中的情况就是如此。

  这里的ValueOperation依赖于RedisTemplate,而在RedisTemplate中可以对RedisConnectionFactory和序列化方式进行设置。在Spring Boot中,用于构建RedisTemplate的代码一般会放到Bootstrap类中,如上面的SpringRedisApplication就是如此。

  在这里,由于我们在使用Redis时是采用的默认配置,所以说此处就没必要配置application.yml文件了。而在默认的配置信息中,Redis服务器是以6378为端口号进行启动。

你可能感兴趣的:(SpringCloud微服务2)