企业 SpringBoot+SpringCloud(九)springboot整合Redis

引入依赖:

在pom文件中添加redis依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>复制代码

配置数据源

spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=
spring.redis.database=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=500
spring.redis.pool.min-idle=0
spring.redis.timeout=0复制代码

如果你的redis有密码,配置下即可。经过上述两步的操作,你可以访问redis数据了。

数据访问层dao

通过redisTemplate来访问redis.

@Repository
public class RedisDao {

    @Autowired
    private StringRedisTemplate template;

    public  void setKey(String key,String value){
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key,value,1, TimeUnit.MINUTES);//1分钟过期
    }

    public String getValue(String key){
        ValueOperations<String, String> ops = this.template.opsForValue();
        return ops.get(key);
    }
}复制代码

单元测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRedisApplicationTests {

    public static Logger logger= LoggerFactory.getLogger(SpringbootRedisApplicationTests.class);
    @Test
    public void contextLoads() {
    }

    @Autowired
    RedisDao redisDao;
    @Test
    public void testRedis(){
        redisDao.setKey("name","forezp");
        redisDao.setKey("age","11");
        logger.info(redisDao.getValue("name"));
        logger.info(redisDao.getValue("age"));
    }
}复制代码

启动单元测试,你发现控制台打印了:

forezp 11

复制代码

单元测试通过;

资料和源码来源地址

Spring Cloud大型企业分布式微服务云架构源码请加企鹅求求:一七九一七四三三八零

转载于:https://juejin.im/post/5c7396326fb9a049e4135770

<think>好的,用户想了解如何将SpringBootSpringCloud、Mybatis-Plus、PostgreSQL、Redis和XXL-Job这些技术栈集成和使用。首先,我需要回顾一下用户之前提供的简历技术描述,里面有提到微服务架构、分布式数据同步、任务调度等,所以用户可能是在实际项目中需要整合这些技术,尤其是在构建高可用、分布式的系统。 用户的问题涉及多个技术点,我需要分步骤来解答,确保每个组件的集成方法清晰。首先,SpringBootSpringCloud作为基础框架,搭建微服务架构是关键。需要说明如何创建SpringBoot项目,并引入SpringCloud的组件,比如服务发现、配置中心、熔断器等。接着是Mybatis-Plus与PostgreSQL的集成,这里要提到依赖配置、数据源设置、实体和Mapper的创建,以及事务管理。 然后是Redis的集成,用户可能用它做缓存或分布式锁,需要说明配置Redis连接、使用注解缓存,以及Redisson的高级功能。XXL-Job作为分布式任务调度平台,需要指导如何部署调度中心,配置执行器,并创建定时任务。此外,微服务间的通信和组件整合也很重要,比如Feign或Dubbo的使用,以及如何结合Redis和XXL-Job优化任务处理。 还要考虑用户提到的性能优化和工程化实践,比如使用Elasticsearch优化查询,Kafka处理数据同步,这些虽然不在当前问题中,但可能在后续扩展中有用。需要确保回答结构清晰,每个部分都有代码示例和配置说明,同时结合用户简历中的技术亮点,比如量化成果和架构设计,增强实用性。 最后,检查是否有遗漏的组件或常见问题,比如版本兼容性、配置细节,以及如何测试和监控这些集成的组件。确保引用之前提到的案例,如使用Resilience4j熔断,或者CRDT解决数据冲突,来增强回答的可信度。同时,提供相关问题,帮助用户深入理解可能遇到的挑战和优化方向。</think>以下为SpringBoot+SpringCloud+Mybatis-Plus+PostgreSQL+Redis+XXL-Job技术栈集成方案,包含架构设计、关键配置与最佳实践: --- ### 一、基础框架集成 #### 1. SpringBootSpringCloud整合 ```xml <!-- SpringCloud Alibaba依赖 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>2021.0.5.0</version> </dependency> <!-- SpringCloud Gateway --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> ``` - 使用Nacos实现服务注册发现,配置示例: ```yaml spring: cloud: nacos: discovery: server-addr: 127.0.0.1:8848 namespace: dev ``` #### 2. Mybatis-Plus集成PostgreSQL ```yaml # 动态数据源配置 spring: datasource: dynamic: primary: master datasource: master: url: jdbc:postgresql://localhost:5432/db_main driver-class-name: org.postgresql.Driver username: postgres password: 123456 ``` - 实体类注解示例: ```java @Data @TableName("t_device") public class Device { @TableId(type = IdType.ASSIGN_ID) private Long id; private String deviceCode; @TableField("status") private Integer deviceStatus; } ``` --- ### 二、Redis深度集成 #### 1. Redisson分布式锁 ```java @Bean public RedissonClient redissonClient() { Config config = new Config(); config.useSingleServer() .setAddress("redis://127.0.0.1:6379") .setDatabase(0); return Redisson.create(config); } // 业务使用示例 public void updateDeviceStatus(Long deviceId) { RLock lock = redissonClient.getLock("DEVICE_LOCK:" + deviceId); try { if(lock.tryLock(5, 30, TimeUnit.SECONDS)) { // 业务逻辑 } } finally { lock.unlock(); } } ``` #### 2. 缓存一致性方案 ```java @Cacheable(value = "device_cache", key = "#deviceId", unless = "#result == null") public Device getDeviceById(Long deviceId) { return baseMapper.selectById(deviceId); } @CacheEvict(value = "device_cache", key = "#device.id") public void updateDevice(Device device) { baseMapper.updateById(device); } ``` --- ### 三、XXL-Job分布式任务 #### 1. 调度中心配置 ```properties # 执行器配置 xxl.job: admin.addresses: http://127.0.0.1:8080/xxl-job-admin accessToken: default_token executor: appname: device-service address: ip: port: 9999 logpath: /data/applogs/xxl-job/jobhandler logretentiondays: 30 ``` #### 2. 任务处理器示例 ```java @XxlJob("deviceStatusSyncJob") public void deviceStatusSyncJob() { // 分片策略 int shardIndex = XxlJobHelper.getShardIndex(); int shardTotal = XxlJobHelper.getShardTotal(); List<Device> devices = deviceService.getDevicesByShard(shardIndex, shardTotal); devices.forEach(device -> { // 同步逻辑 }); } ``` --- ### 四、微服务通信优化 #### 1. OpenFeign增强配置 ```java @FeignClient(name = "inspection-service", configuration = FeignConfig.class) public interface InspectionClient { @PostMapping("/api/inspection/create") Result<Boolean> createInspectionTask(@RequestBody InspectionDTO dto); } // 熔断配置 public class InspectionClientFallback implements InspectionClient { @Override public Result<Boolean> createInspectionTask(InspectionDTO dto) { return Result.fail("服务降级"); } } ``` #### 2. 分布式事务方案 ```java // 使用Seata AT模式 @GlobalTransactional public void crossServiceOperation() { deviceService.update(); inspectionService.create(); // 异常时自动回滚 } ``` --- ### 五、监控与调试 1. **Prometheus监控配置**: ```yaml management: endpoints: web: exposure: include: health,info,prometheus metrics: tags: application: ${spring.application.name} ``` 2. **XXL-Job执行日志分析**: ```sql -- PostgreSQL日志表结构 CREATE TABLE xxl_job_log ( id BIGSERIAL PRIMARY KEY, job_group INT NOT NULL, job_id INT NOT NULL, executor_address VARCHAR(255), trigger_time TIMESTAMP, trigger_code INT, handle_time TIMESTAMP, handle_code INT ); ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值