Spring boot uses Redis cache

Keywords: Programming Spring Redis Docker Maven

1 redis is installed on linux

  1. Install docker

yum install docker

2) open docker

service docker start

2. Install Redis

Go to this website to find out how to install https://hub.docker.com

Open redis

3 create a springBoot project (details are not covered in detail)

pom.xml file

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	 
<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
	
    <artifactId>spring-boot-starter-parent</artifactId>
	
    <version>2.1.6.RELEASE</version>
	
    <relativePath/> <!-- lookup parent from repository -->
	
</parent>

<groupId>com.mao</groupId>

<artifactId>spring-cache</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>spring-cache</name>

<description>Demo project for Spring Boot</description>

<properties>

    <java.version>1.8</java.version>
	
</properties>

<dependencies>

    <dependency>
	
        <groupId>org.springframework.boot</groupId>
		
        <artifactId>spring-boot-starter-jdbc</artifactId>
		
    </dependency>

    <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>org.mybatis.spring.boot</groupId>
		
        <artifactId>mybatis-spring-boot-starter</artifactId>
		
        <version>2.0.1</version>
		
    </dependency>

    <dependency>
	
        <groupId>mysql</groupId>
		
        <artifactId>mysql-connector-java</artifactId>
		
        <version>5.1.47</version>
		
        <scope>runtime</scope>
		
    </dependency>
	
    <dependency>
	
        <groupId>org.springframework.boot</groupId>
		
        <artifactId>spring-boot-starter-test</artifactId>
		
        <scope>test</scope>
		
    </dependency>
	
</dependencies>

<build>
    <plugins>
	
        <plugin>
		
            <groupId>org.springframework.boot</groupId>
			
            <artifactId>spring-boot-maven-plugin</artifactId>
			
        </plugin>
		
    </plugins>
	
</build>

</project>

4. Provide an entity class / / this file is from the shangxue school.

public class Employee implements Serializable

private Integer id;

private String lastName;

private String email;

private Integer gender; //Gender 1 male 0 female

private Integer dId;

... and... (abbreviated)

}

5. For redis customers, please install it yourself

Relevant knowledge points can be learned on this website http://www.redis.cn There are many cases in it

6 configuration property application.properties

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring_cache

spring.datasource.username=root

spring.datasource.password=123456

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#Starting hump nomenclature

mybatis.configuration.map-underscore-to-camel-case=true

logging.level.mao.springcache.mapper=debug

#Because the redis I installed doesn't have a password, just give the host address.

spring.redis.host=192.168.1.139

7 test the Redis cache. First, see how the source code is written.

public class SpringCacheApplicationTests {

//Operation key value pair, the default serialization mechanism of jdk

@Autowired

RedisTemplate redisTemplate;

//Operation string

@Autowired

StringRedisTemplate stringRedisTemplate;

@Autowired

RedisTemplate<Object,Employee> redisTemplate1;

[@Test](https://my.oschina.net/azibug)
public void test1(){
    //stringRedisTemplate.opsForValue().append("hello","hello");
    System.out.println(stringRedisTemplate.opsForValue().get("hello"));

}
 [@Test](https://my.oschina.net/azibug)
public void test2(){
    Employee employee = employeeMapper.getEmployee(1);

    redisTemplate.opsForValue().set("emp-01",employee);
}
@Test
public void contextLoads() {
    Employee employee = employeeMapper.getEmployee(1);
    System.out.println(employee.toString());
}

}

Test result of test1 above:

The above test2 test results:

Next, solve the ugly problem above: we rewrite RedisTemplate, and we want the cache to be json when viewing.

@Configuration

public class myredis {

@Bean

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

    RedisTemplate<Object,Employee> template = new RedisTemplate<Object, Employee>();
	
    template.setConnectionFactory(redisConnectionFactory);
	
    Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
	
    template.setDefaultSerializer(ser);
	
    return template;
}
}

The principle has been shown in the previous picture.

The following figure explains the sentence Hal template. Setdefaultserializer (SER);

Retest results

8 next, I'll talk about using in spring project //EmployeeService class

@Service

public class EmployeeService {

@Autowired

EmployeeMapper employeeMapper;

//Cache the result of the method, request the same data in the future, and get it directly from the cache without calling the method

//CacheManager manages multiple Cache components. Each Cache group has its own unique name for the real CRUD component of the Cache.

//Several attributes, specifying the cache name key, can specify @ param id

@Cacheable(cacheNames ={"emp"})

public Employee getEmp(Integer id){

    System.out.println("query"+id+"staff");
	
    Employee employee = employeeMapper.getEmployee(id);
	
    return  employee;
}

//The cache is updated synchronously. The key to get the cache is the same as the key to put the cache.

@CachePut(cacheNames = "emp",key = "#employee.id")

public Employee updateEmp(Employee employee){

    employeeMapper.updateEmp(employee);
	
    return employee;
}
@CacheEvict(value = "emp",key = "#id")

public  void deleteEmp(Integer id){

    System.out.println("deleteEMp"+id);
	

public Employee getEmployeeByLastName(String lastName){

   return employeeMapper.getEmpByLastName(lastName);
}

}

EmployeeMapper code

public interface EmployeeMapper {

@Select("select * from employee where id =#{id}")

public Employee getEmployee(Integer id);

@Update("update employee set lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} where id =#{id}")

public void updateEmp(Employee employee);

@Delete("delete * from employee where id=#{id}")

public void deleteEmpById(Integer id);

@Insert("insert into employee(lastName,email,gender,d_id) values(#{lastName},#{email},#{gender},#{dId})")

public void insertEmpployee(Employee employee);

@Select("select * from employee where lastName=#{lastName}")

public  Employee getEmpByLastName(String name);

}

EmployeeController.java

@RestController

public class EmployeeController {

@Autowired
EmployeeService employeeService;

@RequestMapping("/emp/{id}")

public Employee getEmployee(@PathVariable("id") Integer id){

    Employee employee=employeeService.getEmp(id);
	
    return  employee;
}

@GetMapping("/emp")

public Employee updateEmp(Employee employee){

    System.out.println("Method call for employee update");
	
      Employee employee1 = employeeService.updateEmp(employee);
	  
      return employee1;
}

@GetMapping("/delete")

public String deleteEmp(Integer id){

    System.out.println("Delete information about an employee");
	
      return "Delete staff";
}
@RequestMapping("/emps/{lastName}")

public Employee getByLastName(@PathVariable("lastName") String lastName){

    return employeeService.getEmployeeByLastName(lastName);
}

}

Configuration note of application class

The following is what I want to write most. At that time, I couldn't write the video of shangxuetang. Because of the different versions, I used 2.xxx.

Here is my configured RedisCacheManager

@Configuration

public class myredis {

@Bean

public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory){

   Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
   
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
	
           .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(ser));
		   
          

   RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
     .cacheDefaults(config).build();
   return cacheManager;

}

} This writing is obviously different from 1.xx.

Here is the 2.xx source code

The picture below explains this sentence

RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()

.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(ser));

test result

Posted by kubis on Mon, 28 Oct 2019 09:59:04 -0700