In the third stage, the Day12 redis command springboot integrates redis AOP to implement redis caching

Half bump 2020-11-09 11:30:16
stage day12 day redis command


  1. Redis Introductory cases

=============

1.1 Redis Common use

1.1.1 setex Study

`/**
* 2. demand :
* 1. towards redis Insert data k-v
* 2. by key Set the timeout 60 Seconds after the failure .
* 3. Threads sleep 3 second
* 4. obtain key The remaining survival time of .
*
* Problem description : Is the data bound to be deleted ??????
* Problem specification : If you use redis And when you need to add a timeout In general, the atomic requirements should be met .
* Atomicity : The operation is either successful Or failure . But it has to be done at the same time .
*/
@Test
public void test02() throws InterruptedException {
Jedis jedis = new Jedis("192.168.126.129",6379);
jedis.setex(" Baokemeng ", 60, " Little fire dragon Frog seed ");
System.out.println(jedis.get(" Baokemeng "));
/* Jedis jedis = new Jedis("192.168.126.129",6379);
jedis.set(" Baokemeng ", " Little fire dragon Frog seed ");
int a = 1/0; // There may be something unusual
jedis.expire(" Baokemeng ", 60);
Thread.sleep(3000);
System.out.println(jedis.ttl(" Baokemeng "));*/
}`

1.1.2 setnx

`/**
* 3. Requirements if found key Preexisting time Do not modify data . If key Data is modified when it doesn't exist .
*
*/
@Test
public void test03() throws InterruptedException {
Jedis jedis = new Jedis("192.168.126.129", 6379);
jedis.setnx("aaaa", " test nx Methods ");
/*if(jedis.exists("aaa")){
System.out.println("key Already exist No modification ");
}else {
jedis.set("aaa", " Test data ");
}*/
System.out.println(jedis.get("aaaa"));
}`

1.1.3 set Timeout atomic operation

 `/**
* demand :
* 1. When the user is asked to assign a value , If the data exists, no assignment is made . setnx
* 2. It is required that in the assignment operation , You have to set the timeout time And it requires atomicity setex
*/
@Test
public void test04() throws InterruptedException {
Jedis jedis = new Jedis("192.168.126.129", 6379);
SetParams setParams = new SetParams();
setParams.nx().ex(20);
jedis.set("bbbb", " Implement business operations AAAA", setParams);
System.out.println(jedis.get("bbbb"));
}`

1.1.4 list Set up exercises

 `@Test
public void testList() throws InterruptedException {
Jedis jedis = new Jedis("192.168.126.129", 6379);
jedis.lpush("list", "1","2","3");
System.out.println(jedis.rpop("list"));
}`

1.1.5 redis Transaction control

 `@Test
public void testTx() throws InterruptedException {
Jedis jedis = new Jedis("192.168.126.129", 6379);
//1. Open transaction
Transaction transaction = jedis.multi();
try {
transaction.set("aa", "aa");
// Commit transaction
transaction.exec();
}catch (Exception e){
e.printStackTrace();
// Roll back the transaction
transaction.discard();
}
}`

2. Second kill business logic — Distributed locking mechanism

6988 —1 block 1 Mobile phone 20 It shows that the purchase is successful And paid for 1 Yuan …
problem :
1.tomcat There are multiple servers
2. Database data only 1 Share
3. High concurrency is inevitable .
How to realize the rush purchase …

2.1 Regular lock operation

2.1.1 The reason for oversold

 Insert picture description here

2.1.2 The problem of synchronization lock

explain : Synchronous lock can only solve tomcat Internal problems , Can't solve multiple tomcat Concurrency issues
 Insert picture description here

2.1.3 Distributed locking mechanism

thought :
1. Locks should use third-party operations , Locks should be public .
2. principle : If the lock is being used , Other users can't operate .
3. Strategy : The user to redis Save a key, If redis There is key Someone is using the lock Other users are not allowed to operate . If redis There is no key , I can use the lock .
4. risk : How to solve the deadlock problem . Set the timeout .
 Insert picture description here

  1. SpringBoot Integrate Redis

=====================

3.1 Edit profile redis.pro

explain : Because this configuration is used by other projects , It should be written that jt-common in .
 Insert picture description here

3.2 Edit configuration class

explain : edit redis Configuration class . take Jedis Object to Spring Container management .

`@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class JedisConfig {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private Integer port;
@Bean
public Jedis jedis(){
return new Jedis(host,port);
}
}`

3.3 Object and the JSON conversion ObjectMapper Introduce

3.3.1 Simple object transformation

`/**
* Test the transformation of simple objects
*/
@Test
public void test01() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(100L).setItemDesc(" Product details ")
.setCreated(new Date()).setUpdated(new Date());
// Object to json
String json = objectMapper.writeValueAsString(itemDesc);
System.out.println(json);
//json Convert to object
ItemDesc itemDesc2 = objectMapper.readValue(json, ItemDesc.class);
System.out.println(itemDesc2.getItemDesc());
}`

3.3.2 Set object conversion

 `/**
* Test the transformation of collection objects
*/
@Test
public void test02() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(100L).setItemDesc(" Product details 1")
.setCreated(new Date()).setUpdated(new Date());
ItemDesc itemDesc2 = new ItemDesc();
itemDesc2.setItemId(100L).setItemDesc(" Product details 2")
.setCreated(new Date()).setUpdated(new Date());
List<ItemDesc> lists = new ArrayList<>();
lists.add(itemDesc);
lists.add(itemDesc2);
//[{key:value},{}]
String json = objectMapper.writeValueAsString(lists);
System.out.println(json);
// take json String is converted to an object
List<ItemDesc> list2 = objectMapper.readValue(json, lists.getClass());
System.out.println(list2);
}`

3.4 Editing tools API

`package com.jt.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.pojo.ItemDesc;
import org.springframework.util.StringUtils;
public class ObjectMapperUtil {
/**
* 1. Convert the data passed by users into json strand
* 2. Pass the user json String is converted to an object
*/
private static final ObjectMapper MAPPER = new ObjectMapper();
//1. Convert the data passed by users into json strand
public static String toJSON(Object object){
if(object == null) {
throw new RuntimeException(" The data transmitted is null. Please check ");
}
try {
String json = MAPPER.writeValueAsString(object);
return json;
} catch (JsonProcessingException e) {
// Will check for anomalies , Convert to runtime exception
e.printStackTrace();
throw new RuntimeException(e);
}
}
// demand : What kind of type is required from the user , What kind of object do I return Knowledge of generics
public static <T> T toObj(String json,Class<T> target){
if(StringUtils.isEmpty(json) || target ==null){
throw new RuntimeException(" Parameter cannot be null");
}
try {
return MAPPER.readValue(json, target);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}`

3.5 Cache implementation of commodity classification

3.5.1 Implementation steps

1. Definition Redis Medium key key It must be the only one that cannot repeat . save take key = “ITEM_CAT_PARENTID::70”
2. according to key Go to redis Query in There's data No data
3. No data Then query the database for records Then save the data to redis in Convenient for subsequent use .
4. There's data Indicates that the user is not querying for the first time You can return the cached data directly .

3.5.2 edit ItemCatController

 Insert picture description here

3.5.3 edit ItemCatService

`@Override
public List<EasyUITree> findItemCatListCache(Long parentId) {
//0. Define a common return value object
List<EasyUITree> treeList = new ArrayList<>();
//1. Definition key
String key = "ITEM_CAT_PARENTID::"+parentId;
//2. retrieval redis The server , Whether it contains the key
// Recording time
Long startTime = System.currentTimeMillis();
if(jedis.exists(key)){
// Data exists
String json = jedis.get(key);
Long endTime = System.currentTimeMillis();
// Need to put json String is converted to an object
treeList = ObjectMapperUtil.toObj(json,treeList.getClass());
System.out.println(" from redis Get data in Time consuming :"+(endTime-startTime)+" millisecond ");
}else{
//3. The data doesn't exist Query the database
treeList = findItemCatList(parentId);
Long endTime = System.currentTimeMillis();
//3. Save data to cache
String json = ObjectMapperUtil.toJSON(treeList);
jedis.set(key, json);
System.out.println(" Query the database Time consuming :"+(endTime-startTime)+" millisecond ");
}
return treeList;
}`

3.5.4 Use Redis The speed difference of

 Insert picture description here

  1. AOP Realization Redis cache

================

4.1 How to understand AOP

name : Section oriented programming
effect : Reduce the coupling of code in the system , And in the condition of not changing the original code, the function of the original method is extended .
The formula : AOP = Pointcut expression + Notification method

4.2 Notification type

1. Pre notice Before the target method is executed
2. The rear notice The target method is executed after execution
3. Abnormal notice When an exception is thrown during the execution of the target method
4. Final notice A notice to be executed at any time
characteristic : The four types of notification mentioned above Cannot interfere with the execution of the target method . It is generally used to record the running state of a program . monitor

5. Surrounding the notification A notification method that is executed before and after the target method is executed This method can control whether the target method runs or not .joinPoint.proceed(); Function as powerful .

4.3 Pointcut expression

understand : Pointcut expression is a judgment of whether a program enters the notification (IF)
effect : When the program is running , When the pointcut expression is satisfied, the notification method is executed , Realize business expansion .
species ( How to write it ):

  1. bean(bean The name of bean Of ID) Can only intercept a specific bean object Only one object can be matched

lg: bean(“itemServiceImpl”)

  1. within( Package name . Class name ) within(“com.jt.service.*”) Can match multiple objects

The principle of coarse-grained matching Match by class

 3. execution( return type Package name . Class name . Method name ( parameter list )) The most powerful use
lg : execution(* com.jt.service..*.*(..))
The return value type is arbitrary com.jt.service All methods of all classes under the package will be intercepted .
4.@annotation( Package name . Annotated name ) Match according to the annotation .
版权声明
本文为[Half bump]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云