springboot整合redis注解版本 redis与Mysql实现数据同步

一、实现原理

通过注解形式实现数据库和redis中数据同步 @Cacheable 用于方法上

二、代码实现

1.引入库

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>

2.链接redis服务 配置文件 application.properties

spring.redis.database=10
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=

3、接口调用

重点: @Cacheable(cacheNames = “gatewayHandler”, key = “‘getGatewayHandler’”)
如果 key = “getGatewayHandler” 不加上 ‘getGatewayHandler’ 则会抛出以下异常

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Sep 24 10:07:01 CST 2021
There was an unexpected error (type=Internal Server Error, status=500).
EL1008E: Property or field 'getGatewayHandler' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject' - maybe not public or not valid?
/**
 * @author sean
 * @Description TODO
 * @createTime 2021年09月23日 21:04:00
 */
@RestController
@RequestMapping("/redis/")
public class RedisController {
    
    @Autowired
    private GatewayHandlerDbService gatewayHandlerDbService;

    /**
     * 注解版本缓存数据
     *
     * @return
     */
    @Cacheable(cacheNames = "gatewayHandler", key = "'getGatewayHandler'")
    @GetMapping("/set/handler/")
    public Object getGatewayHandler() {

		//如果 redis中没有则执行该方法去数据库查询,如果redis中有则无需执行该操作
        return gatewayHandlerDbService.searchAll();
    }
}

4.启动类 开始redis缓存注解 @EnableCaching

/**
 * @author sean
 * @createTime 2021年09月23日 20:38:00
 */
@SpringBootApplication
@MapperScan("com.sean.springboot.design.mapper")
//开始redis缓存注解
@EnableCaching
public class RedisApp {
    public static void main(String[] args) {
        SpringApplication.run(RedisApp.class, args);
    }
}

三、有待更新 Mysql 与Redis 一致性解决方案

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是将Redis的哈希同步MySQLSpring Boot代码示例: 1. 添加依赖 在pom.xml文件添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 2. 创建Redis配置类 创建Redis配置类,用于连接Redis,并配置Redis的参数。示例代码如下: ```java @Configuration public class RedisConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Bean public RedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(); config.setHostName(host); config.setPort(port); return new JedisConnectionFactory(config); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory()); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` 3. 创建MySQL实体类 创建MySQL实体类,并使用JPA注解配置实体类和数据表映射关系。示例代码如下: ```java @Entity @Table(name = "user_info") public class UserInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; private String address; // 省略getter和setter方法 } ``` 4. 创建MySQL数据访问接口 创建MySQL数据访问接口,并使用JPA注解配置接口方法和数据表映射关系。示例代码如下: ```java public interface UserInfoRepository extends JpaRepository<UserInfo, Long> { } ``` 5. 编写同步逻辑 编写同步逻辑代码,从Redis获取哈希数据,遍历哈希数据,并将数据同步MySQL数据。示例代码如下: ```java @Service public class RedisSyncService { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private UserInfoRepository userInfoRepository; public void syncHashToMySQL(String hashKey) { Map<Object, Object> redisHash = redisTemplate.opsForHash().entries(hashKey); for (Map.Entry<Object, Object> entry : redisHash.entrySet()) { UserInfo userInfo = new UserInfo(); userInfo.setName(entry.getKey().toString()); String value = entry.getValue().toString(); JSONObject object = JSONObject.parseObject(value); userInfo.setAge(object.getInteger("age")); userInfo.setAddress(object.getString("address")); userInfoRepository.save(userInfo); } } } ``` 6. 初始化调用 在Spring Boot的启动类初始化调用同步逻辑,将Redis的哈希数据同步MySQL。示例代码如下: ```java @SpringBootApplication public class Application implements CommandLineRunner { @Autowired private RedisSyncService redisSyncService; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { redisSyncService.syncHashToMySQL("redis-hash-key"); } } ``` 以上是将Redis的哈希同步MySQLSpring Boot代码示例。具体实现可能因业务需求而异,仅供参考。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值