Java combat spingboot-redis

Continuing with the previous series, this section, we roll up springboot framework on how to use redis

 

pom.xml file dependent redis introduced, the introduction of sequence-dependent

  The introduction of serialization dependence, we are trying to get on a project from the database to the entity, serialized in the Redis

 

 

 

application.yml file to make configuration redis

  Note: I have here is a cluster configuration, of course, you can also configure a single point there is no problem

 

 

 

Modified controller code

 

 

 

 

 With code:

package com.ncat.webdemo.controller;

import com.ncat.webdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ncat.webdemo.pojo.User;

import java.time.Duration;

@RestController
@RequestMapping(value = {"user"})
public class UserController {

@Autowired
private UserService userService;

@Autowired
RedisTemplate redisTemplate;

@RequestMapping(value = {"test"})
public User Test(@RequestParam Integer id) {

String redisKey = "Test:User:" + id;

// key序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
//val实例化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

ValueOperations<String, User> operations = redisTemplate.opsForValue();

if (redisTemplate.hasKey(redisKey)) {
return operations.get(redisKey);
} else {
User user = userService.selectByPrimaryKey(id);
operations.set(redisKey, user, Duration.ofSeconds(300));
return user;
}
}
}

Browser running

 

 

   Error analysis, should be our User entity can not be serialized lead

Let entities User implements Serializable

 

 

 Run again

 

 

 Successful, we look at Redis

 

 

 It can also be found in the

 

Guess you like

Origin www.cnblogs.com/nigthcat/p/11458657.html