• 68685

    文章

  • 645

    评论

  • 65

    友链

  • 最近新加了换肤功能,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

SpringBoot 使用Redis缓存

撸了今年阿里、腾讯和美团的面试,我有一个重要发现.......>>

1 redis是安装在linux上

  1. 安装docker

yum install docker

2)开启docker

service docker start

2 安装Redis

可到这个网站查怎么安装 https://hub.docker.com

开启redis

3 创建springBoot项目(细节不在赘述)

pom.xml文件

<?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 提供一个entity类 //这个文件来自尚学堂里的

public class Employee implements Serializable

private Integer id;

private String lastName;

private String email;

private Integer gender; //性别 1男  0女

private Integer dId;

。。。。。。(简写啦)

}

5 redis的客户请自己安装

相关知识点请到这个网站学习 http://www.redis.cn 里面有很多案例

6 配置属性 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

#启动驼峰命名法

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

logging.level.mao.springcache.mapper=debug

#由于我安装的redis没密码,只给主机地址就可以啦

spring.redis.host=192.168.1.139

7 测试下Redis的缓存首先看下源码是怎么写的

public class SpringCacheApplicationTests {

//操作键值对,jdk默认的序列化机制

@Autowired

RedisTemplate redisTemplate;

//操作字符串

@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());
}

}

上面test1测试结果:

上面test2测试结果:

接下来解决上面难看的问题:我们重写RedisTemplate 我们想让缓存查看的时候为json

@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;
}
}

之前一张图已经展示过原理

下面这张图解释这句haul template.setDefaultSerializer(ser);

重新测试的结果

8 接下啦讲spring项目中使用 //EmployeeService类

@Service

public class EmployeeService {

@Autowired

EmployeeMapper employeeMapper;

//将方法的结果缓存,以后请求相同的数据,直接从缓存中获取,不用调用方法

//CacheManner管理多个Cache组件,对缓存的真正CRUD组件,每个缓存组有自己唯一一个名字

//几个属性,指定缓存的名字key,可以指定@param id

@Cacheable(cacheNames ={"emp"})

public Employee getEmp(Integer id){

    System.out.println("查询"+id+"员工");
	
    Employee employee = employeeMapper.getEmployee(id);
	
    return  employee;
}

//达到了同步更新缓存的目的,取缓存的key要与放缓存的key相同

@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代码

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("员工更新的方法调用");
	
      Employee employee1 = employeeService.updateEmp(employee);
	  
      return employee1;
}

@GetMapping("/delete")

public String deleteEmp(Integer id){

    System.out.println("删除一个员工的相关信息");
	
      return "删除员工";
}
@RequestMapping("/emps/{lastName}")

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

    return employeeService.getEmployeeByLastName(lastName);
}

}

应用类的配置 注意

下面是我最想写的,当时看尚学堂的视频一直写不出来的,由于使用的版本不同,我使用的使用2.xxx

下面是我配置的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;

}

} 这个写法和1.xx明显不同

下面是2.xx源码

下面这副图解释这句

RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()

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

测试结果


 转载至链接:https://my.oschina.net/u/2511906/blog/3073590。

695856371Web网页设计师②群 | 喜欢本站的朋友可以收藏本站,或者加入我们大家一起来交流技术!

欢迎来到梁钟霖个人博客网站。本个人博客网站提供最新的站长新闻,各种互联网资讯。 还提供个人博客模板,最新最全的java教程,java面试题。在此我将尽我最大所能将此个人博客网站做的最好! 谢谢大家,愿大家一起进步!

转载原创文章请注明出处,转载至: 梁钟霖个人博客www.liangzl.com

0条评论

Loading...


发表评论

电子邮件地址不会被公开。 必填项已用*标注

自定义皮肤
注册梁钟霖个人博客