`
sillycat
  • 浏览: 2560990 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Spring Boot and RESTful API(5)Redis

 
阅读更多
Spring Boot and RESTful API(5)Redis

Redis Connection

scan only supported after 2.8.0
https://redis.io/commands/scan

I am using /opt/redis-2.6.14. I need to update my Redis on local machine first.
>wget http://download.redis.io/releases/redis-3.2.9.tar.gz
unzip the file and build the binary
>make
>mkdir /Users/carl/tool/redis-3.2.9
>mkdir /Users/carl/tool/redis-3.2.9/bin
>mkdir /Users/carl/tool/redis-3.2.9/conf

>cp src/redis-server /Users/carl/tool/redis-3.2.9/bin/
>cp src/redis-benchmark /Users/carl/tool/redis-3.2.9/bin/
>cp src/redis-cli /Users/carl/tool/redis-3.2.9/bin/
>cp redis.conf /Users/carl/tool/redis-3.2.9/conf/

Start the Server
>nohup bin/redis-server conf/redis.conf &

Configuration and Code for Spring Redis
pom.xml to include the package
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

YAML configuration file application.yaml
spring:
    profiles:
        active: dev
    redis:
        database: 0
        host: localhost 
        port: 6379

Directly have a test Class on the RedisTemplate, RedisTemplateTest.java
package com.sillycat.jobsmonitorapi.repository;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTemplateTest {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Test
    public void testStringCRUD() {
        String key = "language";
        String value = "java";
        this.redisTemplate.opsForValue().set(key, value);
        String result1 = redisTemplate.opsForValue().get(key);
        Assert.isTrue(value.equals(result1), "Wrong data from Redis");
        this.redisTemplate.delete(key);
        String result2 = redisTemplate.opsForValue().get(key);
        Assert.isNull(result2, "Data is not deleted successfully from Redis");
    }

    @Test
    public void testScanning() {
        this.redisTemplate.opsForValue().set("cache_geo_lat_long_info_by_zipcode_13434", "1");
        this.redisTemplate.opsForValue().set("cache_geo_lat_long_info_by_zipcode_12", "2");
        this.redisTemplate.opsForValue().set("cache_geo_lat_long_info_by_zipcode_1234", "2");

        String pattern = "cache_geo_lat_long_info_by_zipcode_*";
        ScanOptions.ScanOptionsBuilder scanOptionsBuilder = new ScanOptions.ScanOptionsBuilder();
        scanOptionsBuilder.match(pattern);
       
        Cursor<byte[]> cursors = this.redisTemplate.getConnectionFactory().getConnection().scan(scanOptionsBuilder.build());
        for(;cursors.hasNext();){
            String tempKey = new String(cursors.next());
            if(tempKey.length() == "cache_geo_lat_long_info_by_zipcode_".length() + 4){
                System.out.println("find and deleting----------------" + tempKey);
                redisTemplate.delete(tempKey);
            }
        }
        String result1 = redisTemplate.opsForValue().get("cache_geo_lat_long_info_by_zipcode_1234");
        Assert.isNull(result1, "Data is not deleted successfully from Redis");
    }
}

Serializer Object
sample POJO
package
com.sillycat.jobsmonitorapi.domain;
import java.io.Serializable;

public class User implements Serializable{

private static final long serialVersionUID = -4062728253774262930L;
private String userName;
private Integer age;

public User(String userName, Integer age){
    this.userName = userName;
    this.age = age;
}
..snip.. getter and setter
}

Redis Helper
package com.sillycat.jobsmonitorapi.repository;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

public class RedisObjectSerializer implements RedisSerializer<Object> {

    private Converter<Object, byte[]> serializer = new SerializingConverter();
    private Converter<byte[], Object> deserializer = new DeserializingConverter();
    static final byte[] EMPTY_ARRAY = new byte[0];

    public Object deserialize(byte[] bytes) {
        if (isEmpty(bytes)) {
            return null;
        }
        try {
            return deserializer.convert(bytes);
        } catch (Exception ex) {
            throw new SerializationException("Cannot deserialize", ex);
        }
    }

    public byte[] serialize(Object object) {
        if (object == null) {
            return EMPTY_ARRAY;
        }
        try {
            return serializer.convert(object);
        } catch (Exception ex) {
            return EMPTY_ARRAY;
        }
    }

    private boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }

}

Redis Config

package com.sillycat.jobsmonitorapi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.sillycat.jobsmonitorapi.domain.User;
import com.sillycat.jobsmonitorapi.repository.RedisObjectSerializer;

@Configuration
public class RedisConfig {

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, User> template = new RedisTemplate<String, User>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }

}

Extend the Tester
package com.sillycat.jobsmonitorapi.repository;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;

import com.sillycat.jobsmonitorapi.domain.User;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTemplateTest {

    @Autowired
    RedisTemplate<String, String> redisTemplateString;

    @Autowired
    RedisTemplate<String, User> redisTemplateUser;

    @Test
    public void testStringCRUD() {
        String key = "language";
        String value = "java";
        this.redisTemplateString.opsForValue().set(key, value);
        String result1 = redisTemplateString.opsForValue().get(key);
        Assert.isTrue(value.equals(result1), "Wrong data from Redis");
        this.redisTemplateString.delete(key);
        String result2 = redisTemplateString.opsForValue().get(key);
        Assert.isNull(result2, "Data is not deleted successfully from Redis");
    }

    @Test
    public void testScanning() {
        this.redisTemplateString.opsForValue().set("cache_geo_lat_long_info_by_zipcode_13434", "1");
        this.redisTemplateString.opsForValue().set("cache_geo_lat_long_info_by_zipcode_12", "2");
        this.redisTemplateString.opsForValue().set("cache_geo_lat_long_info_by_zipcode_1234", "2");

        String pattern = "cache_geo_lat_long_info_by_zipcode_*";
        ScanOptions.ScanOptionsBuilder scanOptionsBuilder = new ScanOptions.ScanOptionsBuilder();
        scanOptionsBuilder.match(pattern);

        Cursor<byte[]> cursors = this.redisTemplateString.getConnectionFactory().getConnection()
                .scan(scanOptionsBuilder.build());
        for (; cursors.hasNext();) {
            String tempKey = new String(cursors.next());
            if (tempKey.length() == "cache_geo_lat_long_info_by_zipcode_".length() + 4) {
                redisTemplateString.delete(tempKey);
            }
        }
        String result1 = redisTemplateString.opsForValue().get("cache_geo_lat_long_info_by_zipcode_1234");
        Assert.isNull(result1, "Data is not deleted successfully from Redis");
    }

    @Test
    public void testObjectUser() {
        User user1 = new User("sillycat", 35);
        redisTemplateUser.opsForValue().set(user1.getUserName(), user1);
        User user2 = new User("kiko", 30);
        redisTemplateUser.opsForValue().set(user2.getUserName(), user2);

        Assert.isTrue(redisTemplateUser.opsForValue().get(user1.getUserName()).getAge().equals(user1.getAge()),
                "age not equal");
        Assert.isTrue(
                redisTemplateUser.opsForValue().get(user2.getUserName()).getUserName().equals(user2.getUserName()),
                "username not equal");
    }

}



Bean Mapping
http://orika-mapper.github.io/orika-docs/intro.html

Learn from org.springside.modules.utils.mapper.BeanMapper

References:
https://stackoverflow.com/questions/17162725/spring-data-redis-redistemplate-exception/30484834#30484834
http://blog.didispace.com/springbootredis/
http://docs.spring.io/spring-data/redis/docs/1.6.2.RELEASE/reference/html/


分享到:
评论

相关推荐

    Springboot+SpringSecurity+SpringSession+Redis+Mybatis-Plus+Swwager.zip

    Plus+Swwager”整合了Spring Boot、Spring Security、Spring Session、Redis、Mybatis-Plus以及Swagger等技术,旨在构建一个强大的、安全的、具有会话管理功能的后端服务,并提供了清晰的API文档。 首先,Spring ...

    spring-boot mybaits spring security redis

    根据提供的标题、描述、标签以及部分链接内容,我们可以推断出该主题主要涉及Spring Boot、MyBatis、Spring Security和Redis等技术栈的综合运用。接下来,我们将详细探讨这些技术的关键知识点及其在实际项目中的应用...

    spring-boot-api-project-seed:Spring Boot API Project Seed 是一个基于Spring Boot & MyBatis的种子项目,可作为权限脚手架项目,集成Shiro+Redis+JWT+MyBatis-Plus

    简介Spring Boot API Project Seed 是一个基于Spring Boot & MyBatis的种子项目,用于快速构建中小型API、RESTful API项目,该种子项目已经有过多个真实项目的实践,稳定、简单、快速,使我们摆脱那些重复劳动,专注...

    spring boot整合redis demo代码

    在控制器中,我们可以调用服务层的方法来与Redis交互,比如一个简单的RESTful API来设置和获取键值对: ```java @RestController @RequestMapping("/redis") public class RedisController { @Autowired private...

    Spring Boot实战派(源码)

    - 使用`@RestController`和`@RequestMapping`注解创建RESTful API。 - Thymeleaf、FreeMarker或Velocity模板引擎进行视图渲染。 - Spring MVC的模型-视图-控制器模式,实现业务逻辑和表示层的分离。 6. **数据...

    Learning Spring Boot 2.0 Second Edition

    接着,作者会深入探讨Spring Boot中的Web开发,包括使用Spring MVC构建RESTful API,处理HTTP请求和响应,以及使用Thymeleaf、FreeMarker等模板引擎进行视图渲染。同时,书中也会介绍Spring Boot的安全组件——...

    spring boot,mybaits,spring security,redis整合

    通过Spring Security,我们可以为RESTful API、Web应用等设定精细的访问控制策略。 Redis则是一款高性能的键值存储系统,常被用作缓存和消息中间件。它可以极大地提升应用的响应速度,通过存储热点数据减少数据库...

    Spring Boot 教程、技术栈示例代码,快速简单上手教程。

    - `spring-boot-web-example`:展示如何创建一个简单的 RESTful API。 - `spring-boot-data-jpa-example`:演示如何使用 Spring Data JPA 和 Hibernate 进行数据库操作。 - `spring-boot-security-example`:介绍...

    Springboot+redis+mybatisplus实例

    在一个具体的应用中,例如电商网站,Spring Boot负责整体架构,提供RESTful API。Redis可以作为商品详情页的缓存,减少数据库访问压力。当用户浏览商品时,先从Redis获取数据,如果没有再从数据库查询并存入Redis。...

    使用springboot,mongodb,redis搭建的高性能restfulAPI项目,开发快速

    在本项目中,我们主要利用Spring Boot、MongoDB和Redis三个关键组件来构建一个高性能的RESTful API服务。下面将详细解析这些技术及其在项目中的应用。 **Spring Boot** Spring Boot是Spring框架的一个子项目,旨在...

    spring boot 相关技术

    3. **Web 开发**:讲解如何使用 Spring Boot 开发 Web 应用,包括 RESTful API 和 Thymeleaf 模板引擎的使用。 4. **数据访问**:涵盖 Spring Data JPA 和 Hibernate 的集成,以及如何操作数据库,包括事务管理。 ...

    spring boot+Vue全栈开发实战

    4. **Chapter 05**: 可能涵盖了Spring Boot的RESTful API开发,如何使用Spring MVC和Controller创建HTTP端点,以及JSON数据的序列化和反序列化。 5. **Chapter 08**: 这一章可能涉及Spring Boot的安全管理,如...

    JavaEE开发的颠覆者 Spring Boot实战 完整版.zip

    2. **Web开发**:介绍如何使用Spring Boot开发RESTful API,集成Thymeleaf或Freemarker进行模板渲染,以及使用WebSocket实现实时通信。 3. **数据访问**:涵盖JPA和MyBatis的集成,数据库连接池的配置,以及事务...

    Netty+Spring Boot仿微信 全栈开发高性能后台及客户端

    在本项目中,Spring Boot将作为后端的核心框架,用于提供RESTful API、数据持久化、安全控制等功能。Spring Boot与Spring Cloud结合,还可以实现微服务架构,提高系统的可扩展性和可维护性。 3. 全栈开发: 全栈...

    Spring Boot Cookbook(2015.09)源码

    3. **4658_03_Code**:这部分可能涵盖了Spring Boot的Web开发,包括使用Spring MVC构建RESTful API,处理HTTP请求和响应,以及模板引擎(如Thymeleaf或Freemarker)的使用。 4. **4658_04_Code**:可能涉及到数据...

    spring Boot 2 精髓

    另一方面,当系统模块增加,性能和吞吐量要求增加时,如何平滑地用Spring Boot实现分布式架构,也会在本书后半部分介绍,包括使用Spring实现RESTful架构,在Spring Boot框架下使用Redis、MongoDB、ZooKeeper、...

    Spring Boot 简绍1

    微服务架构是一种软件开发方法,它提倡将单一应用程序拆分为一组小的服务,每个服务运行在其自己的进程中,并且服务间通过轻量级通信机制(如 RESTful API)进行交互。这种架构强调服务的独立部署、独立开发和独立...

    电商平台秒杀系统的设计与实现-基于Vue、Spring Boot、MySQL和Redis的技术方案

    该项目利用了Vue.js进行前端开发,采用Spring Boot构建RESTful API来处理各种业务逻辑,并用MySQL作为主数据库存储持久化的数据,Redis提供高性能缓存能力,最后配合RabbitMQ来辅助高并发情况下的消息通讯。...

    基于spring boot的个人博客网站项目+ppt

    1. **RESTful API**:后端提供RESTful风格的API接口,供前端调用,实现前后端分离。这样做的好处是前后端可以独立开发和部署,提高了开发效率和可维护性。 2. **安全控制**:可以使用Spring Security来实现用户认证...

    Spring Boot 2精髓带书签目录高清版

    文字可复制,内容丰富,涵盖Spring Boot框架、Spring MVC、视图技术、数据库访问技术,并且介绍多环境部署、自动装配、单元测试等高级特性,包括使用Spring实现RESTful架构,在Spring Boot框架下使用Redis、MongoDB...

Global site tag (gtag.js) - Google Analytics