首页 文章 精选 留言 我的

精选列表

搜索[SpringBoot],共4361篇文章
优秀的个人博客,低调大师

Springboot整合redis从安装到FLUSHALL

语言: java+kotlin windows下安装redis 参考 https://www.cnblogs.com/jaign/articles/7920588.html 安装redis可视化工具 Redis Desktop Manager 参考 https://www.cnblogs.com/zheting/p/7670154.html 依赖 compile('org.springframework.boot:spring-boot-starter-data-redis') application.yml配置 spring: # redis redis: database: 0 host: localhost port: 6379 password: 12345 jedis: pool: max-active: 10 min-idle: 0 max-idle: 8 timeout: 10000 redis配置类 new RedisConfiguration package com.futao.springmvcdemo.foundation.configuration import org.springframework.cache.CacheManager import org.springframework.cache.annotation.CachingConfigurerSupport import org.springframework.cache.annotation.EnableCaching import org.springframework.cache.interceptor.KeyGenerator import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.redis.cache.RedisCacheManager import org.springframework.data.redis.connection.RedisConnectionFactory import org.springframework.data.redis.core.RedisTemplate import org.springframework.data.redis.serializer.StringRedisSerializer import javax.annotation.Resource /** * redis配置类 * * @author futao * Created on 2018/10/16. * * redisTemplate.opsForValue();//操作字符串 * redisTemplate.opsForHash();//操作hash * redisTemplate.opsForList();//操作list * redisTemplate.opsForSet();//操作set * redisTemplate.opsForZSet();//操作有序set * */ @Configuration @EnableCaching open class RedisConfiguration : CachingConfigurerSupport() { /** * 自定义redis key的生成规则 */ @Bean override fun keyGenerator(): KeyGenerator { return KeyGenerator { target, method, params -> val builder = StringBuilder() builder.append("${target.javaClass.simpleName}-") .append("${method.name}-") for (param in params) { builder.append("$param-") } builder.toString().toLowerCase() } } /** * 自定义序列化 * 这里的FastJsonRedisSerializer引用的自己定义的 */ @Bean open fun redisTemplate(factory: RedisConnectionFactory): RedisTemplate<String, Any> { val redisTemplate = RedisTemplate<String, Any>() val fastJsonRedisSerializer = FastJsonRedisSerializer(Any::class.java) val stringRedisSerializer = StringRedisSerializer() return redisTemplate.apply { defaultSerializer = fastJsonRedisSerializer keySerializer = stringRedisSerializer hashKeySerializer = stringRedisSerializer valueSerializer = fastJsonRedisSerializer hashValueSerializer = fastJsonRedisSerializer connectionFactory = factory } } @Resource lateinit var redisConnectionFactory: RedisConnectionFactory override fun cacheManager(): CacheManager { return RedisCacheManager.create(redisConnectionFactory) } } 自定义redis中数据的序列化与反序列化 new FastJsonRedisSerializer package com.futao.springmvcdemo.foundation.configuration import com.alibaba.fastjson.JSON import com.alibaba.fastjson.serializer.SerializerFeature import com.futao.springmvcdemo.model.system.SystemConfig import org.springframework.data.redis.serializer.RedisSerializer import java.nio.charset.Charset /** * 自定义redis中数据的序列化与反序列化 * * @author futao * Created on 2018/10/17. */ class FastJsonRedisSerializer<T>(java: Class<T>) : RedisSerializer<T> { private val clazz: Class<T>? = null /** * Serialize the given object to binary data. * * @param t object to serialize. Can be null. * @return the equivalent binary data. Can be null. */ override fun serialize(t: T?): ByteArray? { return if (t == null) { null } else { JSON.toJSONString(t, SerializerFeature.WriteClassName).toByteArray(Charset.forName(SystemConfig.UTF8_ENCODE)) } } /** * Deserialize an object from the given binary data. * * @param bytes object binary representation. Can be null. * @return the equivalent object instance. Can be null. */ override fun deserialize(bytes: ByteArray?): T? { return if (bytes == null || bytes.isEmpty()) { null } else { val string = String(bytes, Charset.forName(SystemConfig.UTF8_ENCODE)) JSON.parseObject(string, clazz) as T } } } 使用 1. 基于注解的方式 @Cacheable() redis中的key会根据我们的keyGenerator方法来生成,比如对应下面这个例子,如果曾经以mobile,pageNum,pageSize,orderBy的值执行过list这个方法的话,方法返回的值会存在redis缓存中,下次如果仍然以相同的mobile,pageNum,pageSize,orderBy的值来调用这个方法的话会直接返回缓存中的值 @Service public class UserServiceImpl implements UserService { @Override @Cacheable(value = "user") public List<User> list(String mobile, int pageNum, int pageSize, String orderBy) { PageResultUtils<User> pageResultUtils = new PageResultUtils<>(); final val sql = pageResultUtils.createCriteria(User.class.getSimpleName()) .orderBy(orderBy) .page(pageNum, pageSize) .getSql(); return userDao.list(sql); } } 测试 第一次请求(可以看到执行了sql,数据是从数据库中读取的) 通过redis desktop manager查看redis缓存中已经存储了我们刚才list返回的值 后续请求(未执行sql,直接读取的是redis中的值) 2. 通过java代码手动set与get package com.futao.springmvcdemo.controller import com.futao.springmvcdemo.model.entity.User import org.springframework.data.redis.core.RedisTemplate import org.springframework.http.MediaType import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import javax.annotation.Resource /** * @author futao * Created on 2018/10/17. */ @RestController @RequestMapping(path = ["kotlinTest"], produces = [MediaType.APPLICATION_JSON_UTF8_VALUE]) open class KotlinTestController { @Resource private lateinit var redisTemplate: RedisTemplate<Any, Any> /** * 存入缓存 */ @GetMapping(path = ["setCache"]) open fun cache( @RequestParam("name") name: String, @RequestParam("age") age: Int ): User { val user = User().apply { username = name setAge(age.toString()) } redisTemplate.opsForValue().set(name, user) return user } /** * 获取缓存 */ @GetMapping(path = ["getCache"]) open fun getCache( @RequestParam("name") name: String ): User? { return if (redisTemplate.opsForValue().get(name) != null) { redisTemplate.opsForValue().get(name) as User } else null } } 测试结果 请求(序列化) redis desktop manager中查看 读取(反序列化) 坑 使用注解的方式存入的数据使用redis desktop manager或者redis-cli --raw查看显示的是编码之后的,但是使用java代码手动set并不会出现这样的问题(后期需要检查使用注解的方式是不是走了自定义的序列化) TODO redis数据的持久化

优秀的个人博客,低调大师

如何用 SpringBoot 优雅的写代码

1. DTO的使用 如果你的controller代码写成这样 @RequestMapping("/user") public List query(@RequestParam String username, @RequestParam String password, @RequestParam int age){ List<User> users = new ArrayList<>(); users.add(new User()); users.add(new User()); users.add(new User()); return users; } 那你就需要了解一下什么是DTO了。 用DTO后的代码 @RequestMapping("/user") public List query(UserQueryCondition condition){ System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.DEFAULT_STYLE)); List<User> users = new ArrayList<>(); users.add(new User()); users.add(new User()); users.add(new User()); return users; } 2. 如何使用PageAble设置默认分页属性 你是不是还是在方法体里声明Pageable对象固定属性呢? 更优雅的在这里:@PageableDefault(page = 2,size = 7,sort = "username,asc")Pageable pageable 3. 如何再@RequestMapping注解上写正则 @RequestMapping("/user/{id:\\d+}") id只能是数字 4. @JsonView注解自定义返回内容 比如User类有两个属性,一个username一个password。 我们想在controller返回里,返回User实体的时候不返回password属性。 4.1 设置视图 首先需要在实体类里声明两个接口 public interface UserSimpleView{}; public interface UserDetailView extends UserSimpleView{}; 然后,在一定要显示的字段的get方法上添加@JsonView(UserSimpleView.class)注解。 在不一定要显示的字段的get方法上添加@JsonView(UserDetailView .class)注解。 User.java 完整代码 public class User { // jsonView 设置视图 public interface UserSimpleView{}; public interface UserDetailView extends UserSimpleView{}; private String useranme; private String password; @JsonView(UserSimpleView.class) public String getUseranme() { return useranme; } public void setUseranme(String useranme) { this.useranme = useranme; } @JsonView(UserDetailView.class) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } 注意getUseranme方法上的注解和getPassword上注解的不同。 4.2 将实体类的get方法上的注解和Controller里相对应 如果controller只想返回username字段,则 @RequestMapping("/user/{id:\\d+}") @JsonView(User.UserSimpleView.class) public User getInfo(@PathVariable int id){ User user = new User(); user.setUseranme("FantJ"); return user; } 如果想返回全部的User属性信息,则 @RequestMapping("/user/{id:\\d+}") @JsonView(User.UserDetailView.class) public User getInfo(@PathVariable int id){ User user = new User(); user.setUseranme("FantJ"); return user; } 上面这个controller方法,我们看到@JsonView(User.UserDetailView.class)所以它会。如果变成返回全部的User属性信息@JsonView(User.UserSimpleView.class),它就只返回username字段信息。因为User类和Controller类中@JsonView注解一一对应。 5. 判断某个字段不为空 我们都知道,post方法,需要用@RequestBody接收实体类信息。如果我们再方法里判断某个属性是否为空然后再抛错,必然增加代码量,不美观。所以我们可以配合几个注解来达到我们的要求。 5.1 首先在实体类字段上添加注解@NotBlank @NotBlank //不为空的注解 private String password; 5.2 在Controller里的@RequestBody前加注解@Valid @PostMapping("/user") public User create(@Valid @RequestBody User user){} 但是光这两个注解作用下,如果密码出现了空值,程序会直接报错,我们希望程序可以正常运行,然后把报错信息打印出来就可以,于是我们还需要加一个类。BindingResult 5.3 添加BindingResult参数 @PostMapping("/user") public User create(@Valid @RequestBody User user, BindingResult errors){} 那如何获取错误信息呢?看下面的完整代码。 5.4 完整代码 @PostMapping("/user") public User create(@Valid @RequestBody User user, BindingResult errors){ user.setId("1"); //打印错误信息 if (errors.hasErrors()){ errors.getAllErrors().stream().forEach(p-> System.out.println(p.getDefaultMessage())); } System.out.println(user.getId()); System.out.println(user.getUseranme()); System.out.println(user.getPassword()); return user; } 但是你一看控制台打印信息你会发现may not be empty,你都不知道是什么字段为空报错的,我们我们把字段信息打印出来。但是又显得代码很长。所以我们可以用@NotBlank的message属性来自定义message。 除了@NotBlank外,还有一些类似常用的注解。 @NotNull 值不能为空 @NotEmpty 字符串不能为空,集合不能为空 @Range(min=,max=) 数字必须大于min小鱼max @Max(value=) 设置最大值同理还有 @Min(value=) @Email 字符必须是Email类型 @Length(min= ,max= ) 字符串长度设置 @URL 字符串是url 6 自定义注解简便开发 介绍下我的所有文集: 流行框架 SpringCloudspringbootnginxredis 底层实现原理: Java NIO教程Java reflection 反射详解Java并发学习笔录Java Servlet教程jdbc组件详解Java NIO教程Java语言/版本 研究

资源下载

更多资源
腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册