SpringCloud使用redis做数据缓存。

1.Docer ToolBox安装redis

生产环境建议redis安装在linux下,这里是为了演示。(性能问题)

docker pull redis

运行redis

docker run -d -p 6379:6379 --name redis --restart=always --privileged=true redis

查看redis版本

docker exec -it redis redis-server -v

进入redis内部

docker exec -it redis /bin/bash

无密码

redis-cli

有密码的情况
auth 你设置的redis密码
在这里插入图片描述

2.创建springcloud应用

老方法直接先拷贝一下,前面章节的服务提供者。
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 https://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.3.0.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.lac</groupId>
	<artifactId>redis-cache</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>redis-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-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-starter-alibaba-nacos-discovery -->
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
			<version>2.2.1.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			</dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>
		<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.68</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Hoxton.SR5</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

<artifactId>redis-cache</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>redis-cache</name>
先把前面服务提供者的这两项改掉。
然后添加
		<dependency>
		<groupId>redis.clients</groupId>
		<artifactId>jedis</artifactId>
		</dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
    </dependency>
    两个依赖。

然后 application.yml配置redis连接信息。

spring:
  application:
    name: redis-cache
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.99.100:8848
  redis:
    database: 0
    host: 192.168.99.100
    port: 6379
    password:
    timeout: 500
    pool:
      max-active: 20
      max-wait: -1
      max-idle: 8
      min-idle: 0
#  cloud:
#    zookeeper:
#      connect-string: 192.168.99.100:2181
#      discovery:
#        enabled: true
server:
    port: 6390

给启动类,添加注解。@EnableCaching
ComponentApplication.java

package com.lac.component;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
@EnableCaching
public class ComponentApplication {

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

}

controller
DemoController.java

package com.lac.component.controller;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    @GetMapping("/")
    public String getHello() {
        return "hello";
    }
    @GetMapping("/user/{string}")
    public String test(@PathVariable String string) {
        return "Hello Nacos :" + string;
    }
    @GetMapping("/cached/{str}")
    @Cacheable(value = "cached",key = "#str")
    public String caching(@PathVariable String str) {
    	System.out.println("未走缓存"+ str);
    	return "hello redis-cache:"+ str;
    }
    @GetMapping("/deleteCacheAll")
    @CacheEvict(value="cached", allEntries=true)
    public String deleteCacheAll() {
    	System.out.println("清空所有缓存");
    	return "delete All redis-cache";
    }
    @GetMapping("/deleteCache/{str}")
    @CacheEvict(cacheNames = "cached", key = "#str")
    public String deleteCache(@PathVariable String str) {
    	System.out.println("删除单个缓存"+ str);
    	return "delete redis-cache:"+ str;
    }
}

@Cacheable是先查询后缓存,
@CacheEvict是删除缓存。
在这里插入图片描述
多次访问路径,只有一次,说明缓存成功
在这里插入图片描述
在这里插入图片描述
多次访问,在这里插入图片描述
缓存成功,由此可以换成你的数据库SQL查询。
在这里插入图片描述
再来个删除一个的。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
删除所有缓存
在这里插入图片描述
在这里插入图片描述
完成了,就是这么简单。

符合你口味的毒鸡汤:

个性定律:在单位里,一个人的个性与他的业务能力成正比。一个人的业务能力越强,个性也就越强,反之就越没有个性。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud 是一个基于 Spring 框架的开发工具集,其中包含了许多开箱即用的组件和库,用于快速开发分布式系统。 要将 Spring Cloud 与 Redis 集成,您需要使用 Spring Data Redis 库。Spring Data Redis 提供了与 Redis 交互的 API,它是一个面向对象的 Redis 数据访问库,可以简化与 Redis 的集成和操作。 以下是将 Spring Cloud 与 Redis 集成的一些步骤: 1. 在 pom.xml 文件中添加 Spring Data Redis 的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在 application.yml 文件中添加 Redis 的配置信息: ``` spring: redis: host: your-redis-host port: your-redis-port password: your-redis-password ``` 3. 使用 @EnableCaching 注解启用 Spring 缓存,并配置 Redis 缓存管理器: ``` @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory).build(); return redisCacheManager; } } ``` 4. 在需要缓存的方法上使用 @Cacheable 注解,指定缓存的 key 和缓存的名称: ``` @Service public class UserService { @Autowired private UserRepository userRepository; @Cacheable(value = "userCache", key = "#id") public User getUserById(Long id) { return userRepository.findById(id).orElse(null); } } ``` 通过以上步骤,您可以在 Spring Cloud 项目中集成 Redis,实现数据缓存的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值