SpringBoot + Redis Easy to make demo

Introduction

I think springboot is the easiest framework for java developers to use. redis is one of the popular NOSQL DBs. This time I will make a demo of CURD using springboot and redis.

Advance preparation

    1. environment:      SpringBoot      Redis      Gradle
  1. Project construction Ask Spring Initializr to automatically generate a project template.

Please set as follows.    ① Gradle Project    ② Java    ③ Spring Boot 2.1.5

Spring_project.jpg

What i did

    1. First, in order to install the library for the project, make the following settings. ① Open the build.gradle file and set it in the form of key-value as shown below.
   dependencies {
      implementation('org.springframework.boot:spring-boot-starter-data-redis')
      implementation('org.springframework.boot:spring-boot-starter-web')
      testImplementation('org.springframework.boot:spring-boot-starter-test')
   }
  1. Redis service placement Open application.properties and add the following contents. (You don't have to have a password.)
   server.port=8088
   spring.redis.database=0
   spring.redis.host=localhost
   spring.redis.port=6379
   spring.redis.password=
   spring.redis.timeout=200
    1. The implemented source.     First, create RedisConfig.java,
@Configuration
public class RedisConfig {

@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
    RedisTemplate<String,Object> template = new RedisTemplate <>();
    template.setConnectionFactory(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);

    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    //String-like ordering method for key
    template.setKeySerializer(stringRedisSerializer);
    //Hash-like key String-like ordering method
    template.setHashKeySerializer(stringRedisSerializer);
    //value serialization method jackson
    template.setValueSerializer(jackson2JsonRedisSerializer);
    //hash-like value ordering method jackson
    template.setHashValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
  }
}

After that, create RedisService.java and implement various functions.

    @Service
    public class RedisService {

      /**
       *Injection redis Template bean
       */
      @Autowired
      private RedisTemplate<String,Object> redisTemplate;

      /**
       *Cache removal
       *
       * @param key Can 传 1 piece or many pieces
       */
      @SuppressWarnings("unchecked")
      public void del(String... key) {
        if (key != null && key.length > 0) {
          if (key.length == 1) {
            redisTemplate.delete(key[0]);
          } else {
            redisTemplate.delete(CollectionUtils.arrayToList(key));
          }
        }
      }

      /**
       *Ordinary cache
       *
           * @param key key
       * @return 值
           */
      public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
      }

      /**
       *Ordinary cache
       *
       * @param key key
       * @param value 值
       * @return true success false dismissal
       */
      public boolean set(String key, Object value) {
        try {
          redisTemplate.opsForValue().set(key, value);
          return true;
        } catch (Exception e) {
          e.printStackTrace();
          return false;
        }
      }
}

Finally, I made a controller to test the function.

@RestController
@RequestMapping(value = "/redis")
public class RedisController {
    /**
     *Injection redis Template bean
     */
      @Autowired
      private RedisService redisService;

      /**
       *Save(update)Data
       * @param key
       * @param value
       * @return
       */
      @RequestMapping(value="/add",method=RequestMethod.GET)
      public String add(String key,String value) {
          redisService.set(key, value);

          return "add successfully";
      }

      /**
       *Specified number of data
       * @param key
       * @return
       */
      @GetMapping(value="/delete")
      public String delete(String key) {

          redisService.del(key);
          return "delete successfully";
      }

      /**
       *Specified number of data
       * @param key
       * @return
       */
      @GetMapping(value="/get")
      public String get(String key) {
          return redisService.get(key)==null ? "data don't exist!" :     redisService.get(key).toString();
      }
}

test

First, start the Redis server with redis-server redis.windows.conf. It looks like this:  redis.jpg

Then start the project.   ① Test the save function Testator: {city: tokyo} URL : localhost:8088/redis/add?key=city&value=tokyo Enter the test URL in your browser and when you access it you will see that it saves successfully. Number of saved data.jpg

② Test the acquisition function   URL : localhost:8088/redis/get?key=city You see, get the data you saved earlier.

Data collection.jpg

③ Test the delete function   URL : localhost:8088/redis/delete?key=city

Delete the saved data.

删除数据.jpg

This is the end of the test.

Finally

If you are interested in this article, download the source here by all means.

Original article site: http://160.16.146.245/u/hyman/blogs/11

that's all

Recommended Posts

SpringBoot + Redis Easy to make demo
Easy to make Slack Bot in Java
Create assert_equal to make it easy to write tests
Easy to make LINE BOT with Java Servlet
How to make shaded-jar
Easy to maintain FizzBuzz
Let's write how to make API with SpringBoot + Docker from 0
Java --How to make JTable
Easy to create Processing library
To make heavy queries asynchronously
[Rails] How to make seed
Easy to use array.map (&: method)
How to identify the path that is easy to make a mistake