从零搭建 Spring Boot 后端项目(三)

亦凉 2023-02-28 05:42 236阅读 0赞

简介

这一小节主要是,整合Redis,需要提前在开发机上安装好Redis才能进行以下操作

步骤

这里我用的是Windows下的 redis 3.0,可以自行下载安装适合自己系统的redis

  • 添加Redis依赖

    1. <!-- redis -->
    2. <dependency>
    3. <groupId>org.springframework.boot</groupId>
    4. <artifactId>spring-boot-starter-data-redis</artifactId>
    5. <version>1.4.5.RELEASE</version>
    6. </dependency>
  • 在 application-dev.properties 下添加如下配置

    1. # Redis
    2. # Redis服务器地址
    3. spring.redis.host=127.0.0.1
    4. # Redis连接端口
    5. spring.redis.port=6379
    6. # Redis连接密码(默认为空)
    7. spring.redis.password=password
    8. # 连接池最大连接数(使用负值表示没有限制)
    9. spring.redis.jedis.pool.max-active=20
    10. # 连接池最大阻塞等待时间(使用负值表示没有限制)
    11. spring.redis.jedis.pool.max-wait=-1
    12. # 连接池中的最大空闲连接、最小空闲连接
    13. spring.redis.jedis.pool.max-idle=10
    14. spring.redis.jedis.pool.min-idle=0
    15. # 连接超时时间(毫秒)
    16. spring.redis.timeout=1000
  • com.example.backend_template.config下新建RedisConfigurer类

    1. package com.example.backend_template.config;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
    6. import org.springframework.cache.annotation.CachingConfigurerSupport;
    7. import org.springframework.cache.annotation.EnableCaching;
    8. import org.springframework.context.annotation.Bean;
    9. import org.springframework.context.annotation.Configuration;
    10. import org.springframework.data.redis.connection.RedisPassword;
    11. import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
    12. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
    13. import org.springframework.data.redis.core.RedisTemplate;
    14. import org.springframework.data.redis.core.StringRedisTemplate;
    15. /**
    16. * @ClassName RedisConfigurer Redis的配置类
    17. * @Description
    18. * @Author L
    19. * @Date Create by 2020/6/26
    20. */
    21. @Configuration
    22. @EnableCaching //开启缓存
    23. public class RedisConfigurer extends CachingConfigurerSupport {
    24. /**
    25. * redis 的各种配置信息,由框架注入
    26. */
    27. @Autowired
    28. private RedisProperties redisProperties;
    29. /**
    30. * 日志工具
    31. */
    32. private static final Logger log = LoggerFactory.getLogger(RedisConfigurer.class);
    33. @Bean
    34. public JedisConnectionFactory getConnectionFactory() {
    35. RedisStandaloneConfiguration redisStandaloneConfiguration =
    36. new RedisStandaloneConfiguration(redisProperties.getHost(), redisProperties.getPort());
    37. redisStandaloneConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
    38. JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration);
    39. log.info("The hostname of the redis connection is:{}, and the port is: {}", factory.getHostName(), factory.getPort());
    40. return factory;
    41. }
    42. public RedisTemplate<?, ?> getRedisTemplate() {
    43. RedisTemplate<?, ?> template = new StringRedisTemplate(getConnectionFactory());
    44. return template;
    45. }
    46. }
  • com.example.backend_template.service下新建RedisService类

    1. package com.example.backend_template.service;
    2. import java.util.List;
    3. /**
    4. * @ClassName RedisService Redis常用方法
    5. * @Description
    6. * @Author L
    7. * @Date Create by 2020/6/26
    8. */
    9. public interface RedisService {
    10. /**
    11. * 设置给定 key 的值。如果 key 已经存储其他值, SET 就覆写旧值,且无视类型。
    12. * @param key
    13. * @param value
    14. * @return
    15. */
    16. boolean set(String key, String value);
    17. /**
    18. * 获取指定 key 的值。如果 key 不存在,返回 nil 。如果key 储存的值不是字符串类型,返回一个错误。
    19. * @param key
    20. * @return
    21. */
    22. String get(String key);
    23. /**
    24. * 设置 key 的过期时间。key 过期后将不再可用。
    25. * @param key
    26. * @param expire
    27. * @return
    28. */
    29. boolean expire(String key, long expire);
    30. /**
    31. * 存集合
    32. * @param key
    33. * @param list
    34. * @param <T>
    35. * @return
    36. */
    37. <T> boolean setList(String key, List<T> list);
    38. /**
    39. * 取集合
    40. * @param key
    41. * @param clz
    42. * @param <T>
    43. * @return
    44. */
    45. <T> List<T> getList(String key, Class<T> clz);
    46. /**
    47. * 将一个或多个值插入到列表头部。 如果 key 不存在,一个空列表会被创建并执行 LPUSH 操作。
    48. * 当 key 存在但不是列表类型时,返回一个错误。
    49. * @param key
    50. * @param obj
    51. * @return
    52. */
    53. long lpush(String key, Object obj);
    54. /**
    55. * 将一个或多个值插入到列表的尾部(最右边)。
    56. * 如果列表不存在,一个空列表会被创建并执行 RPUSH 操作。 当列表存在但不是列表类型时,返回一个错误。
    57. * @param key
    58. * @param obj
    59. * @return
    60. */
    61. long rpush(String key, Object obj);
    62. /**
    63. * 移除并返回列表的第一个元素。
    64. * @param key
    65. * @return
    66. */
    67. String lpop(String key);
    68. /**
    69. * 删除已存在的键。不存在的 key 会被忽略。
    70. * @param key
    71. * @return
    72. */
    73. long del(final String key);
    74. }
  • com.example.backend_template.service.impl下新建RedisServiceImpl类,这里需要alibaba的fastjson包,所示要提前有pom.xml添加如下依赖

    1. <!-- fastjson -->
    2. <dependency>
    3. <groupId>com.alibaba</groupId>
    4. <artifactId>fastjson</artifactId>
    5. <version>1.2.41</version>
    6. </dependency>
    7. package com.example.backend_template.service.impl;
    8. import com.alibaba.fastjson.JSON;
    9. import com.example.backend_template.service.RedisService;
    10. import org.springframework.dao.DataAccessException;
    11. import org.springframework.data.redis.connection.RedisConnection;
    12. import org.springframework.data.redis.core.RedisCallback;
    13. import org.springframework.data.redis.core.RedisTemplate;
    14. import org.springframework.data.redis.serializer.RedisSerializer;
    15. import org.springframework.stereotype.Service;
    16. import javax.annotation.Resource;
    17. import java.util.List;
    18. import java.util.concurrent.TimeUnit;
    19. /**
    20. * @ClassName RedisServiceImpl
    21. * @Description
    22. * @Author L
    23. * @Date Create by 2020/6/26
    24. */
    25. @Service
    26. public class RedisServiceImpl implements RedisService {
    27. @Resource
    28. private RedisTemplate<String, ?> redisTemplate;
  1. @Override
  2. public boolean set(final String key, final String value) {
  3. boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
  4. @Override
  5. public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
  6. RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
  7. connection.set(serializer.serialize(key), serializer.serialize(value));
  8. return true;
  9. }
  10. });
  11. return result;
  12. }
  13. @Override
  14. public String get(final String key){
  15. String result = redisTemplate.execute(new RedisCallback<String>() {
  16. @Override
  17. public String doInRedis(RedisConnection connection) throws DataAccessException {
  18. RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
  19. byte[] value = connection.get(serializer.serialize(key));
  20. return serializer.deserialize(value);
  21. }
  22. });
  23. return result;
  24. }
  25. @Override
  26. public long del(final String key){
  27. long result = redisTemplate.execute(new RedisCallback<Long>() {
  28. @Override
  29. public Long doInRedis(RedisConnection connection) throws DataAccessException {
  30. RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
  31. long value = connection.del(serializer.serialize(key));
  32. return value;
  33. }
  34. });
  35. return result;
  36. }
  37. @Override
  38. public boolean expire(final String key, long expire) {
  39. return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
  40. }
  41. @Override
  42. public <T> boolean setList(String key, List<T> list) {
  43. String value = JSON.toJSONString(list);
  44. return set(key,value);
  45. }
  46. @Override
  47. public <T> List<T> getList(String key,Class<T> clz) {
  48. String json = get(key);
  49. if(json!=null){
  50. List<T> list = JSON.parseArray(json, clz);
  51. return list;
  52. }
  53. return null;
  54. }
  55. @Override
  56. public long lpush(final String key, Object obj) {
  57. final String value = JSON.toJSONString(obj);
  58. long result = redisTemplate.execute(new RedisCallback<Long>() {
  59. @Override
  60. public Long doInRedis(RedisConnection connection) throws DataAccessException {
  61. RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
  62. long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));
  63. return count;
  64. }
  65. });
  66. return result;
  67. }
  68. @Override
  69. public long rpush(final String key, Object obj) {
  70. final String value = JSON.toJSONString(obj);
  71. long result = redisTemplate.execute(new RedisCallback<Long>() {
  72. @Override
  73. public Long doInRedis(RedisConnection connection) throws DataAccessException {
  74. RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
  75. long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));
  76. return count;
  77. }
  78. });
  79. return result;
  80. }
  81. @Override
  82. public String lpop(final String key) {
  83. String result = redisTemplate.execute(new RedisCallback<String>() {
  84. @Override
  85. public String doInRedis(RedisConnection connection) throws DataAccessException {
  86. RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
  87. byte[] res = connection.lPop(serializer.serialize(key));
  88. return serializer.deserialize(res);
  89. }
  90. });
  91. return result;
  92. }
  93. }

测试

  • com.example.backend_template.controller下新建RedisController类

    1. package com.example.backend_template.controller;
    2. import com.example.backend_template.service.RedisService;
    3. import org.springframework.web.bind.annotation.GetMapping;
    4. import org.springframework.web.bind.annotation.PostMapping;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. import javax.annotation.Resource;
    8. /**
    9. * @ClassName RedisController
    10. * @Description
    11. * @Author L
    12. * @Date Create by 2020/6/26
    13. */
    14. @RestController
    15. @RequestMapping("redis")
    16. public class RedisController {
    17. @Resource
    18. private RedisService redisService;
    19. @PostMapping("/setRedis")
    20. public Boolean setRedis(String name) {
    21. return redisService.set("name", name);
    22. }
    23. @GetMapping("/getRedis")
    24. public String getRedis() {
    25. return redisService.get("name");
    26. }
    27. }
  • 启动项目,请求方式为POST,URL为 http://localhost:8080/redis/setRedis ,参数名为name,如下图方式进行访问
    在这里插入图片描述
  • 请求方式为GET,URL为 http://localhost:8080/redis/getRedis 如下图方式进行访问
    在这里插入图片描述
    如出现如上两种结果,则表示Redis已整合成功

项目地址

项目介绍:从零搭建 Spring Boot 后端项目
代码地址:https://github.com/xiaoxiamo/backend-template

下一篇

四、整合 Spring Security

发表评论

表情:
评论列表 (有 0 条评论,236人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring Boot 项目

    简介 一个基于 Spring Boot 的后端开发模板,主要用于减少平时重复的工作量,以及使开发有良好的开发规范,主要功能包括但不限于权限管理、在线接口文档、日志记录、单