爆破专栏丨SpringBoot2(26)

文章介绍了如何在SpringBoot项目中创建User实体类、数据库操作仓库、服务层接口和服务实现,以及如何使用Lombok和SpringDataJPA进行CRUD操作。特别关注了如何利用注解实现缓存功能,包括`@Cacheable`、`@CachePut`和`@CacheEvict`。此外,还提及了与Kafka的相关性,尽管主体是关于SpringBoot应用开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

* @Author 一一哥Sun
 * @Date Created in 2020/4/14
 * @Description Description
 * EnableCaching启用缓存
 */ 
@Configuration
@EnableCaching
public class CacheConfig {
}


**5. 创建User实体类**


接着创建一个User实体类,封装用户信息。



package com.yyg.boot.domain;

import lombok.Data;
import lombok.ToString;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name=“user”)
@Data
@ToString
public class User implements Serializable {

//IllegalArgumentException: DefaultSerializer requires a Serializable payload
    // but received an object of type [com.syc.redis.domain.User]

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

@Column
    private String username;

@Column
    private String password;

}


**6. 创建User仓库类**


我们再创建一个JpaRepository,实现对数据库的CRUD操作。



package com.yyg.boot.repository;

import com.yyg.boot.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User,Long> {
}


**7. 创建Service服务类**


**7.1 定义UserService接口**



package com.yyg.boot.service;

import com.yyg.boot.domain.User;

public interface UserService {

User findById(Long id);

User save(User user);

void deleteById(Long id);

}


**7.2 实现UserServiceImpl类**



package com.yyg.boot.service.impl;

import com.yyg.boot.domain.User;
import com.yyg.boot.repository.UserRepository;
import com.yyg.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

@Autowired
    private UserRepository userRepository;

//普通的缓存+数据库查询代码实现逻辑:
    //User user=RedisUtil.get(key);
    //   if(user==null){
    //      user=userDao.findById(id);
    //      //redis的key=“product_item_”+id
    //      RedisUtil.set(key,user);
    //   }
    //   return user;

/**
     *  注解@Cacheable:查询的时候才使用该注解!
     *  注意:在Cacheable注解中支持EL表达式
     *  redis缓存的key=user_1/2/3…
     *  redis的缓存雪崩,缓存穿透,缓存预热,缓存更新…
     *  condition = “#result ne null”,条件表达式,当满足某个条件的时候才进行缓存
     *  unless = “#result eq null”:当user对象为空的时候,不进行缓存
     */
    @Cacheable(value = “user”, key = “#id”, unless = “#result eq null”)
    @Override
    public User findById(Long id) {

return userRepository.findById(id).orElse(null);
    }

/**
     * 注解@CachePut:一般用在添加和修改方法中
     * 既往数据库中添加一个新的对象,于此同时也往redis缓存中添加一个对应的缓存.
     * 这样可以达到缓存预热的目的.
     */
    @CachePut(value = “user”, key = “#result.id”, unless = “#result eq null”)
    @Override
    public User save(User user) {
        return userRepository.save(user);
    }

/**
     * CacheEvict:一般用在删除方法中
     */
    @CacheEvict(value = “user”, key = “#id”)
    @Override
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }

}


**8. 创建Controller接口方法**


然后创建一个Controller,定义几个URL接口进行测试。



package com.yyg.boot.web;

import com.yyg.boot.domain.User;
import com.yyg.boot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(“/user”)
@Slf4j
public class UserController {

@Autowired
    private UserService userService;

@PostMapping
    public User saveUser(@RequestBody User user) {
        return userService.save(user);
    }

@GetMapping(“/{id}”)
    public ResponseEntity getUserById(@PathVariable(“id”) Long id) {
        User user = userService.findById(id);
        log.warn(“user=”+user.hashCode());
        HttpStatus status = user == null ? HttpStatus.NOT_FOUND : HttpStatus.OK;
        return new ResponseEntity<>(user, status);
    }

@DeleteMapping(“/{id}”)
    public String removeUser(@PathVariable(“id”) Long id) {
        userService.deleteById(id);
        return “ok”;
    }

}


#### **9. 创建入口类**


最后创建一个项目入口类,启动项目。



package com.yyg.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CacheApplication {

public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }

}


#### **10. 项目代码结构**




## 总结:绘上一张Kakfa架构思维大纲脑图(xmind)

![image](https://img-blog.csdnimg.cn/img_convert/8015c01f6cd5889d45353de7c78c3839.webp?x-oss-process=image/format,png)

其实关于Kafka,能问的问题实在是太多了,扒了几天,最终筛选出44问:基础篇17问、进阶篇15问、高级篇12问,个个直戳痛点,不知道如果你不着急看答案,又能答出几个呢?

若是对Kafka的知识还回忆不起来,不妨先看我手绘的知识总结脑图(xmind不能上传,文章里用的是图片版)进行整体架构的梳理

梳理了知识,刷完了面试,如若你还想进一步的深入学习解读kafka以及源码,那么接下来的这份《手写“kafka”》将会是个不错的选择。

*   Kafka入门

*   为什么选择Kafka

*   Kafka的安装、管理和配置

*   Kafka的集群

*   第一个Kafka程序

*   Kafka的生产者

*   Kafka的消费者

*   深入理解Kafka

*   可靠的数据传递

*   Spring和Kafka的整合

*   SpringBoot和Kafka的整合

*   Kafka实战之削峰填谷

*   数据管道和流式处理(了解即可)

![image](https://img-blog.csdnimg.cn/img_convert/95a16994592c8b833e667ad68feb7900.webp?x-oss-process=image/format,png)

![image](https://img-blog.csdnimg.cn/img_convert/62d8eca8c25bbe2015d3d6fd9f391df1.webp?x-oss-process=image/format,png)

 Kafka的集群

*   第一个Kafka程序

*   Kafka的生产者

*   Kafka的消费者

*   深入理解Kafka

*   可靠的数据传递

*   Spring和Kafka的整合

*   SpringBoot和Kafka的整合

*   Kafka实战之削峰填谷

*   数据管道和流式处理(了解即可)

[外链图片转存中...(img-ndqNbzaa-1714756391022)]

[外链图片转存中...(img-4vY3Myv7-1714756391022)]

> **本文已被[CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】](https://bbs.youkuaiyun.com/topics/618154847)收录**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值