Spring boot整合redis

Spring boot整合redis

Github源码:https://github.com/superRabbitMan/spring-boot-redis

本文基于spring提供的spring-data-redis整合spring boot和redis

引入依赖

<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
   </dependency>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
   <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
   </dependency>

   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
   </dependency>
</dependencies>

配置yml配置文件,添加redis属性配置和配置Bean

# Redis\u914D\u7F6E
spring:
  redis:
    host: 172.16.94.138
    port: 7001
    jedis:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory 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);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public UserRedis userRedis() {
        return new UserRedis();
    }

}

创建实体类

public class User implements Serializable {

    private Long id;

    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

创建UserRedis处理类

@Repository
public class UserRedis {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void add(String key, Long time, User user) {
        Gson gson = new Gson();
        redisTemplate.opsForValue().set(key, gson.toJson(user), time, TimeUnit.MINUTES);
    }

    public void add(String key, Long time, List<User> users) {
        Gson gson = new Gson();
        redisTemplate.opsForValue().set(key, gson.toJson(users), time, TimeUnit.MINUTES);
    }

    public User get(String key) {
        Gson gson = new Gson();
        User user = null;
        String userJson = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(userJson)) {
            user = gson.fromJson(userJson, User.class);
        }
        return user;
    }

    public List<User> getList(String key) {
        Gson gson = new Gson();
        List<User> ts = null;
        String listJson = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(listJson)) {
            ts = gson.fromJson(listJson, new TypeToken<List<User>>(){}.getType());
        }
        return ts;
    }

    public void delete(String key) {
        redisTemplate.opsForValue().getOperations().delete(key);
    }

}

启动类中添加访问方法

当然也可以使用JUnit去测试

@RestController
@SpringBootApplication
public class SpringBootRedisApplication {

   @Autowired
   private UserRedis userRedis;

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

   @RequestMapping(value = "/add")
   public String add() {
      User user = new User();
      user.setId(1L);
      user.setName("rabbit");
      userRedis.add("user", 10L, user);
      return new Gson().toJson(user);
   }

   @RequestMapping(value = "/adds")
   public String adds() {
      List<User> users = new ArrayList<>();
      for (int i = 0; i < 5; i++) {
         User user = new User();
         user.setId(1L * i);
         user.setName("rabbit" + "-" + i);
         users.add(user);
      }
      userRedis.add("users", 10L, users);
      return new Gson().toJson(users);
   }

   @RequestMapping(value = "/get/{key}")
   public String get(@PathVariable(name = "key") String key) {
      return new Gson().toJson(Optional.ofNullable(userRedis.get(key)).orElse(new User()));
   }

   @RequestMapping(value = "/del/{key}")
   public String del(@PathVariable(name = "key") String key) {
      User user = userRedis.get(key);
      userRedis.delete(key);
      return new Gson().toJson(user);
   }

}

关注微信公众号(程序员小兔)不定期分享技术

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie
应支付0元
点击重新获取
扫码支付

支付成功即可阅读